怎么用R语言读取Unicode.CSV?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (3)
  • 关注 (0)
  • 查看 (493)

我有一个.CSV文件,它包含以下数据:

"Ա","Բ"
1,10
2,20

我不能将它读到R中,这样列名就会像在文件中一样显示。

d <- read.csv("./Data/1.csv", fileEncoding="UTF-8")
head(d)

产生以下情况:

> d <- read.csv("./Data/1.csv", fileEncoding="UTF-8")
Warning messages:
1: In read.table(file = file, header = header, sep = sep, quote = quote,  :
  invalid input found on input connection './Data/1.csv'
2: In read.table(file = file, header = header, sep = sep, quote = quote,  :
  incomplete final line found by readTableHeader on './Data/1.csv'
> head(d)
[1] X.
<0 rows> (or 0-length row.names)

同时,在不指定文件编码的情况下进行同样的操作会产生以下结果:

> d <- read.csv("./Data/1.csv")
> head(d)
  Ô. Ô²
1  1 10
2  2 20

当我运行“file”实用程序来查找该文件的编码时,它说它是UTF-8:

Data\1.csv: UTF-8 Unicode text, with CRLF line terminators
提问于
用户回答回答于

我用OpenOffice打开文件并使用“UTF 8”字符集将其保存回(需要单击“编辑筛选设置”框),然后使用read.csv()(没有编码或文件编码选项)。

用户回答回答于

将上面的字符复制到RStudio中,用下面的代码将其保存到CSV中:

write.csv(c("Ա","Բ",
             1,10,
             2,20), "test.csv")

df <- read.csv("test.csv")

把字符粘贴到一个文本文件中,并将其保存为CSV。

这是我的会话信息:

sessionInfo()
R version 3.0.1 (2013-05-16)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
[1] LC_CTYPE=en_CA.UTF-8       LC_NUMERIC=C               LC_TIME=en_CA.UTF-8       
[4] LC_COLLATE=en_CA.UTF-8     LC_MONETARY=en_CA.UTF-8    LC_MESSAGES=en_CA.UTF-8   
[7] LC_PAPER=C                 LC_NAME=C                  LC_ADDRESS=C              
[10] LC_TELEPHONE=C             LC_MEASUREMENT=en_CA.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats4    grid      stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] party_1.0-9       modeltools_0.2-21 strucchange_1.4-7 sandwich_2.2-10   zoo_1.7-10       
[6] GGally_0.4.4      reshape_0.8.4     plyr_1.8          ggplot2_0.9.3.1  

loaded via a namespace (and not attached):
[1] coin_1.0-23        colorspace_1.2-2   dichromat_2.0-0    digest_0.6.3      
[5] gtable_0.1.2       labeling_0.2       lattice_0.20-23    MASS_7.3-29       
[9] munsell_0.4.2      mvtnorm_0.9-9995   proto_0.3-10       RColorBrewer_1.0-5
[13] reshape2_1.2.2     scales_0.2.3       splines_3.0.1      stringr_0.6.2 
用户回答回答于

使用参数编码而不是文件编码。

d <- read.csv("./Data/1.csv", encoding="UTF-8")
head(d)

将表保存到UTF-8文件中:

> test2 <- read.csv("test2.csv", header = FALSE, sep = ",", quote = "\"", dec = ".", fill = TRUE, comment.char = "", encoding = "UTF-8")
Warning message:
In read.table(file = file, header = header, sep = sep, quote = quote,  :
  incomplete final line found by readTableHeader on 'test2.csv'

这给出了控制台和RStudio视图中的样子

> test2
        V1       V2
1 <U+0531> <U+0532>
2        1       10
3        2       20

在我的示例中,可以看到脚本窗口输入具有UTF-8编码,而grep在表中正确地找到了这种编码。

> Encoding("Ա")
[1] "UTF-8"
> grep("Ա", as.character(test2[1,1]))
[1] 1

扫码关注云+社区

领取腾讯云代金券