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

前端 未结 4 1784
花落未央
花落未央 2021-01-13 18:19

Since fwrite() cannot apply encoding argument , how can i export csv file in specific encode as fast as fwrite() ? (fwrite()

4条回答
  •  甜味超标
    2021-01-13 18:52

    I know some people have already answered but I wanted to contribute a more holistic solution using the answer from user2554330.

    # Encode data in UTF-8
    for (col in colnames(DT)) {
        names(DT) <- enc2utf8(names(DT)) # Column names need to be encoded too
        DT[[col]] <- as.character(DT[[col]]) # Allows for enc2utf8() and Encoding()
        DT[[col]] <- enc2utf8(DT[[col]]) # same as users' answer
        Encoding(DT[[col]]) <- "unknown"
    }
    
    fwrite(DT, "DT.csv", bom = T)
    
    # When re-importing your data be sure to use encoding = "UTF-8"
    DT2 <- fread("DT.csv", encoding = "UTF-8") 
    # DT2 should be identical to the original DT
    

    This should work for any and all UTF-8 characters anywhere on a data.table

提交回复
热议问题