Robert Robert - 1 year ago 125
R Question

How to specify the number of decimal places for numeric values written to a file in R?

I want to take this data frame

df <- data.frame(col1 = c(1.224, 1.3), col2 = c(0.8011, 1.90))

and write it to a file so that each numeric value displays exactly two decimal places. I tried the solution given in Controlling digits in R in write.csv, but when I use

write.csv(format(df, digits = 2, nsmall = 2), "./testout.csv")

the numeric values in my file have been converted to strings. So I tried the solution given in Formatting Decimal places in R, as follows:

write.csv(format(round(df, 2), nsmall = 2), "./testout.csv")

but, again, the file shows that my numeric values have been converted to strings.

How can I write this data.frame to a file so that the numeric values are written as numeric values with exactly two decimal places?

Answer Source

You can add quote=FALSE to your write.csv call.

For example:

df[] <- lapply(df, sprintf, fmt='%.02f')
write.csv(df, f <- tempfile(), row.names=FALSE, quote=FALSE)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download