我有一个大表要读入 R,并且该文件采用 .txt
格式。在R中,我使用read.table
函数,但读入时出现错误。出现以下错误消息:
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, :
line 28 did not have 23 elements
看起来(从第一行开始计数,不计算我指定的 skip=
的标题),第 28 行中的数据缺少元素。我正在寻找一种通过过滤掉此行来自动纠正此问题的方法。目前,我什至无法读取该文件,因此我无法在 R 中进行操作...非常感谢任何建议:)
最佳答案
这是我的方法:使用选项 fill=TRUE
调用 read.table
,并排除随后未填充所有字段的行(通过调用到count.fields
)。
示例:
# 1. Data generation, and saving in 'tempfile'
cat("1 John", "2 Paul", "7 Pierre", '9', file = "tempfile", sep = "\n")
# 2. read the data:
data = read.table('tempfile',fill=T)
# 3. exclude incomplete data
c.fields = count.fields('tempfile')
data = data[ - (which(c.fields) != max(c.fields)),]
(编辑以自动获取行数)
关于read.table 函数用于读取 R 中不完整的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22364307/