read.table 函数用于读取 R 中不完整的数据

标签 r read.table

我有一个大表要读入 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/

相关文章:

r - 在文件中获取错误(文件, "rt"): cannot open the connection

使用另一个数据框中的名称重命名列

r - ggplot2中geom_step中线条的边框

r - 使用 read.table 时监控 R 数据加载进度

读取 "next line delimited"的文本文件

r - 将带有多字符分隔符的 "csv"文件导入到 R?

arrays - 命名数组维度会出现错误 : length of 'dimnames' not equal to array extent

python - RPY2:进口商因 .Renviron 失败

r - 在每个面的密度图的中心平均值上画一条线

r - 将选择标准添加到 read.table