windows - 从 R 写入 UTF-8 文件

标签 windows r unicode utf-8

虽然 R 似乎在内部可以很好地处理 Unicode 字符,但我无法在 R 中输出具有此类 UTF-8 Unicode 字符的数据帧。有什么办法可以强制执行此操作吗?

data.frame(c("hīersumian","ǣmettigan"))->test
write.table(test,"test.txt",row.names=F,col.names=F,quote=F,fileEncoding="UTF-8")

输出文本文件如下:

hiersumian <U+01E3>mettigan

我在 Windows 环境 (Windows 7) 中使用 R 版本 3.0.2。

编辑


答案中建议 R 以 UTF-8 正确写入文件,问题出在我用来查看文件的软件上。这是我在 R 中执行所有操作的一些代码。我正在读取以 UTF-8 编码的文本文件,R 可以正确读取它。然后 R 以 UTF-8 写出文件并再次读回,现在正确的 Unicode 字符消失了。

read.table("myinputfile.txt",encoding="UTF-8")->myinputfile
myinputfile[1,1]
write.table(myinputfile,"myoutputfile.txt",row.names=F,col.names=F,quote=F,fileEncoding="UTF-8")
read.table("myoutputfile.txt",encoding="UTF-8")->myoutputfile
myoutputfile[1,1]

控制台输出:

> read.table("myinputfile.txt",encoding="UTF-8")->myinputfile
> myinputfile[1,1]
[1] hīersumian
Levels: hīersumian ǣmettigan
> write.table(myinputfile,"myoutputfile.txt",row.names=F,col.names=F,quote=F,fileEncoding="UTF-8")
> read.table("myoutputfile.txt",encoding="UTF-8")->myoutputfile
> myoutputfile[1,1]
[1] <U+FEFF>hiersumian
Levels: <U+01E3>mettigan <U+FEFF>hiersumian
> 

最佳答案

这个“答案”的目的是澄清幕后发生了一些奇怪的事情:

“hīersumian”似乎甚至没有进入数据框。 “ī”符号在所有情况下都转换为“i”。

options("encoding" = "native.enc")
t1 <- data.frame(a = c("hīersumian "), stringsAsFactors=F)
t1
#             a
# 1 hiersumian 

options("encoding" = "UTF-8")
t1 <- data.frame(a = c("hīersumian "), stringsAsFactors=F)
t1
#             a
# 1 hiersumian 

options("encoding" = "UTF-16")
t1 <- data.frame(a = c("hīersumian "), stringsAsFactors=F)
t1
#             a
# 1 hiersumian 

以下序列成功地将“ǣmettigan”写入文本文件:

t2 <- data.frame(a = c("ǣmettigan"), stringsAsFactors=F)

getOption("encoding")
# [1] "native.enc"

Encoding(t2[,"a"]) <- "UTF-16"

write.table(t2,"test.txt",row.names=F,col.names=F,quote=F)

enter image description here

它不适用于“编码”为“UTF-8”或“UTF-16”,并且指定“fileEncoding”将导致缺陷或无输出。

到目前为止,我设法以某种方式修复了所有 Unicode 问题,这有点令人失望。

关于windows - 从 R 写入 UTF-8 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19877676/

相关文章:

r - 如何确定一个组的重复行,然后选择该组的整个元素

用字符串替换列表中找到的字符串

python - 如何在 python 中检查 Unicode 字符

sql - 有时创建数据库,但有时不创建

php - PHP 可以判断服务器操作系统是否为 64 位吗?

c++ - Windows 7 - CreateProcess w/DEBUG_PROCESS 访问冲突

string - 在 Swift 中转换 Unicode

windows - 如何永久绕过 Windows XP 启动?

R Shiny 观察行取消选择数据表

mysql - 如何在 mysql LOAD DATA INFILE 查询中使用 unicode 字符作为字段分隔符