【问题标题】:read.table function for reading in incomplete data in R用于读取 R 中不完整数据的 read.table 函数
【发布时间】:2014-03-12 21:32:10
【问题描述】:

我有一张大表要读入 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 中进行操作......任何建议都非常感谢:)

【问题讨论】:

    标签: r read.table


    【解决方案1】:

    这是我的做法:使用选项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)),]
    

    (编辑自动获取行数)

    【讨论】:

      【解决方案2】:

      当您的数据中有井号 (#) 时也会发生该错误。

      如果是这种情况,只需将选项 comment.char 更改为 comment.char = ""

      read.table("file.txt", comment.char = "")
      

      【讨论】:

        猜你喜欢
        • 2014-09-13
        • 1970-01-01
        • 2023-02-24
        • 2015-12-12
        • 2016-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多