2

I am trying to write a dataframe as csv, which succeeds, but end up some fields with weird characters, Say for example 4.5×10−7 gives 4.5×10−7 in the csv file. After doing few research I used fileEncoding as "Windows-1252", but that dint help. Here is a reproducible code

name <- c('John Doe','Peter Gynn','Jolie Hope')
valuename <- c("4.5×10−7", "0.0006", "0.345")
df <- data.frame(name,valuename)
write.csv(df, "/Desktop/test.csv", row.names=FALSE)

Can anyone help me with a proper encoding or an alternative to take care of that field?

Gerg
  • 336
  • 4
  • 14

2 Answers2

3

Try to force the fileEncoding to use "UTF-8":

write.csv(df, "/Desktop/test.csv", row.names=FALSE, fileEncoding = 'UTF-8')

Your code works fine in my windows 7, but I already had similar problems on my ubuntu 16.04.

pirs
  • 2,410
  • 2
  • 18
  • 25
  • Looks like when I open in Xcel these weird characters come, but in text wrangler it looks exactly what I wanted. – Gerg Oct 23 '17 at 17:50
2

Using the readr package you can simply use:

readr::write_excel_csv(df, file)

Per the documentation this function "include[s] a UTF-8 Byte order mark which indicates to Excel the csv is UTF-8 encoded."

Brenton M. Wiernik
  • 1,006
  • 4
  • 8
Logit4Life
  • 21
  • 2