Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i specify encode in fwrite() for export csv file R?

Tags:

r

fwrite

Since fwrite() cannot apply encoding argument , how can i export csv file in specific encode as fast as fwrite() ? (fwrite() is the fastest function within my acknowledgement so far)

fwrite(DT,"DT.csv",encoding = "UTF-8")
Error in fwrite(DT, "DT.csv", encoding = "UTF-8") : 
  unused argument (encoding = "UTF-8")
like image 338
rane Avatar asked Sep 28 '18 11:09

rane


1 Answers

You should post a reproducible example, but I would guess you could do this by making sure the data in DT is in UTF-8 within R, then setting the encoding of each column to "unknown". R will then assume the data is encoded in the native encoding when you write it out.

For example,

DF <- data.frame(text = "á", stringsAsFactors = FALSE)
DF$text <- enc2utf8(DF$text) # Only necessary if Encoding(DF$text) isn't "UTF-8"
Encoding(DF$text) <- "unknown"
data.table::fwrite(DF, "DF.csv", bom = TRUE)

If the columns of DF are factors, you'll need to convert them to character vectors before this will work.

like image 137
user2554330 Avatar answered Nov 07 '22 23:11

user2554330