附加时文件编码会发生变化

时间:2017-12-15 05:54:36

标签: r encoding utf-8

我想使用write.table撰写文件,并使用UTF-8作为encoding。只要我不附加到此文件,这就可以工作。当我这样做时,encoding会更改为ANSI。为什么这样,我该如何防止这种情况?

以下是一个小示例代码:

options("encoding" = "UTF-8")
write.table("Hello World in UTF-8", file = "C:/TEMP/test.txt", col.names = FALSE, row.names = FALSE, sep = "", quote = FALSE)
write.table("Now it changes to ANSI", file = "C:/TEMP/test.txt", col.names = FALSE, row.names = FALSE, sep = "", quote = FALSE, append = TRUE) 

我还尝试直接在fileEncoding = "UTF-8"中使用write.table,但结果是一样的。

1 个答案:

答案 0 :(得分:1)

就个人而言,我宁愿不依赖全球option。使用fileEncoding参数write.table可以保护您的代码免受全局option中的任何更改。因此该行应该是:

write.table("Now it changes to ANSI", file = "C:/TEMP/test.txt", col.names = FALSE, row.names = FALSE, sep = "", quote = FALSE, append = TRUE, fileEncoding = "UTF-8")