format columns on data frame in r

Viewed 7815

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)
2 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))

There is also a package called fmtr designed specifically for this situation. It lets you control the formatting for each column independently. There are two main functions fapply() and fdata().

fapply() applies a format to a vector or single column. Like this:

a <- c(3.412324463,3.2452364)
b <- c(2.2342,4.234234)
c1 <- data.frame(A=a, B=b)
c2 <- c1

c2$A <- fapply(c2$A, "%.3f")
c2$B <- fapply(c2$B, "%.4f")

c2

#       A      B
# 1 3.412 2.2342
# 2 3.245 4.2342

fdata() applies formats to an entire data frame. All you have to do is assign the format to the format attribute of the column, and then call of the fdata() function on the data frame. fdata() will apply all the formats assigned, and leave any unformatted columns alone:

c3 <- c1

# Assign formats
attr(c3$A, "format") <- "%.1f"
attr(c3$B, "format") <- "%.2f"

# Apply formats
fdata(c3)

#     A    B
# 1 3.4 2.23
# 2 3.2 4.23

There is also a formats() function that allows you to more easily assign the format attributes to different columns. You just create a named list, where each name corresponds to the column you want to assign formats to. Then you can call the fdata() function like above:

c4 <- c1

# Assign formats
formats(c4) <- list(A = "%.2f",
                    B = "%.1f")
# Apply formats
fdata(c4)

#      A   B
# 1 3.41 2.2
# 2 3.25 4.2

Related