Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format columns on data frame in r

Tags:

format

r

apply

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)
like image 806
Lucas Avatar asked Sep 11 '25 02:09

Lucas


1 Answers

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))
like image 83
akrun Avatar answered Sep 13 '25 15:09

akrun