Search code examples
rfwrite

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


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")

Solution

  • 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.