Search code examples
rexport-to-csv

Force write.csv to include decimal point for numeric data type


Is there a way to include decimal even for integer like values on numeric data types while writing to csv?

f <- tempfile("d", fileext = ".csv")
write.csv(data.frame(x = as.numeric(c(1,2,3.3,4))), f, row.names = FALSE)
readLines(f)
#> [1] "\"x\"" "1"     "2"     "3.3"   "4"
unlink(f)

The above output should have been as below:

#> [1] "\"x\"" "1.0"     "2.0"     "3.3"   "4.0"

Solution

  • write_csv2 from readr does what you expect. Keep in mind that it uses a decimal , instead of a . so read data with e.g. read.csv2.

    library(readr)
    
    write_csv2(data.frame(x = c(1, 2, 3.3, 4)), file = "file")
    
    readLines("file")
    [1] "x"   "1,0" "2,0" "3,3" "4,0"
    
    read.csv2("file")
        x
    1 1.0
    2 2.0
    3 3.3
    4 4.0