1

Writing a csv with the write_csv() function from package readr seems to treat numbers differently depending on trailing zeros.

  • 4001705344 is saved as is, but
  • 4100738000 is saved as 4100738e3 in the csv.

This causes problems when I reopen the csv (e.g. in Excel).

For a reproducible example s.

    library(readr)
    x <- c(4100750938, 4104806156, 4001682199, 4100738000)
    df <- data.frame(x) 
    write_csv(df, "df.csv") 

The result is

    x
    4100750938
    4104806156
    4001682199
    4100738e3

The expected result is

    x
    4100750938
    4104806156
    4001682199
    4100738000

The only thing that helps is to save x as a character vector, which keeps the 000 intact and produces the expected output.

    library(readr)
    x <- c(4100750938, 4104806156, 4001682199, 4100738000)
    x <- as.character(x)
    df <- data.frame(x) 
    write_csv(df, "df.csv") 

But is there another way? And is write_csv() behaving correctly here?

I use readr_1.1.1 on R version 3.3.3 (2017-03-06) Platform: x86_64-w64-mingw32/x64 (64-bit)

Browsing other Questions I found write_csv read_csv with scientific notation after 1000th row but that seems do be a different question to me.

gplngr
  • 77
  • 7
  • Please see : https://github.com/tidyverse/readr/issues/671 If you use integers than you can follow this: https://stackoverflow.com/questions/30341140/readr-turn-off-scientific-notation-in-write-csv – Katia May 16 '18 at 10:49
  • options(digits=18) write.csv(df, "myfile.csv") – Katia May 16 '18 at 10:56
  • Thanks - this works! I try to stay with the readr package - it seems that the devs think about integrating an option or drop the automatic formatting, s. https://github.com/tidyverse/readr/pull/679 – gplngr May 16 '18 at 11:43
  • Great! I added this as an answer. – Katia May 16 '18 at 12:03

2 Answers2

0

Try below code

write_csv(df, "df.csv",fileEncoding = "UTF-16LE")
Prany
  • 2,078
  • 2
  • 13
  • 31
  • This returns Error in write_csv(df, "df.csv", fileEncoding = "UTF-16LE"): unused argument (fileEncoding = "UTF-16LE") Did you mean write.csv(df, "df.csv", fileEncoding = "UTF-16LE")? But this would not return the expected output either. – gplngr May 16 '18 at 11:24
0

One approach is to use regular write.csv() function and set options():

x <- c(4100750938, 4104806156, 4001682199, 4100738000)
df <- data.frame(x) 

options(digits=15) 
write.csv(df, "myfile.csv", row.names = FALSE)

system("cat myfile.csv")
# "x"
# 4100750938
# 4104806156
# 4001682199
# 4100738000
Katia
  • 3,784
  • 1
  • 14
  • 27