1

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?

Community
  • 1
  • 1
Robert
  • 2,111
  • 4
  • 18
  • 32

1 Answers1

2

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)
file.show(f)
jbaums
  • 27,115
  • 5
  • 79
  • 119