R 3.3.2 使用 read.table 导入 CSV 时出错——可能是引用问题

R 3.3.2 Error importing CSV using read.table -- Probable quoting issue

我有一个大型的 csv 数据集,事实证明很难将其导入 R。

下面是数据集的示例,包含所有相关问题:

col 1,col 2,col 3,col 4
txt 1,txt ' 2,"This is a big

field with carriage returns, all enclosed in double

quotes",txt 4
txt1,txt2,txt3,txt4

因此,如您所见,字段中的单引号、包含逗号的大块文本的双引号以及字段中的换行(所有这些都应包含在双引号中)存在问题。但是,如果字段不包含逗号和换行符,则它们没有双引号。

我试过了

read.table(file, sep = ",", quote = '"', header = TRUE)

但是我收到错误

Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  :
  line 31 did not have 95 elements

不确定到底是什么问题,但我确定它与条件双引号文本限定符和/或新行有关。

关于调整代码或如何解决问题的任何建议?感谢任何帮助!

使用 data.table 包中的 fread,它可以很好地使用默认参数:

DF = data.table::fread(data.table = FALSE, "col 1,col 2,col 3,col 4
txt 1,txt ' 2,\"This is a big

field with carriage returns, all enclosed in double

quotes\",txt 4
txt1,txt2,txt3,txt4")

给予

  col 1   col 2                                                                                          col 3 col 4
1 txt 1 txt ' 2 This is a big\n    \n    field with carriage returns, all enclosed in double\n    \n    quotes txt 4
2  txt1    txt2                                                                                           txt3  txt4

我怀疑它可以通过传递给 read.table 的适当参数来完成,但假设您可以安装 data.table 或其他一些可以更好地处理此问题的软件包,这可能不值得麻烦。

我可以在这个玩具示例中做到这一点,但我完全不确定这是正确的方法。我对真实世界的 CSV 文件的经验是,经常有其他故障会破坏这种努力。

xs <- scan( what="", sep=",", quote="\"")
# then paste in your text:

1: col 1,col 2,col 3,col 4
5: txt 1,txt ' 2,"This is a big
5: 
5: field with carriage returns, all enclosed in double
5: 
5: quotes",txt 4
9: txt1,txt2,txt3,txt4
13: 
Read 12 items

(为弗兰克 data.table 的成功点赞。)

因为 read.table 实际上是 scan 函数的包装器,我尝试了这些设置并最终明白我需要在第二行转义内部单引号:

read.table( text='col 1,col 2,col 3,col 4
txt 1,txt \' 2,"This is a big

field with carriage returns, all enclosed in double

quotes",txt 4
txt1,txt2,txt3,txt4
', header=TRUE, sep=",", quote="\"")