I want to format certain columns of a data frame changing decimal mark and number of decimal positions
a <- c(3.412324463,3.2452364)
b <- c(2.2342,4.234234)
c <- data.frame(A=a, B=b)
I can do it column by column but would rather apply it to various columns, also I can not find number of decimals. "digits=2" gives me only to digits, including decimal part
c$A <- format(c$A, decimal.mark = ",",digits = 2)
It is better not to use function names (c
) to name objects. To apply the format
to all the columns
c[] <- lapply(c, format, decimal.mark = ",", digits = 2)
Or with formatC
c[] <- lapply(c, formatC, decimal.mark =",", format = "f", digits = 2)
If we need to apply to selected multiple columns, i.e. columns 1 to 3 and 7:10
j1 <- c(1:3, 7:10)
c[j1] <- lapply(c[j1, formatC, decimal.mark =",", format = "f", digits = 2)
Or another option with sprintf
c[] <- lapply(c, function(x) sub(".", ",", sprintf("%0.2f", x), fixed = TRUE))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With