【问题标题】:Read.table to skip lines with errorsRead.table 跳过有错误的行
【发布时间】:2014-04-05 08:28:42
【问题描述】:

我有一个由制表符分隔的大型 .csv 文件,该文件具有 colClasses = c("integer", "integer", "numeric") 的严格结构。出于某种原因,有许多垃圾无关字符行,打破了模式,这就是我得到的原因

Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  : 
  scan() expected 'an integer', got 'ExecutiveProducers'

我怎样才能让 read.table 继续并跳过这行?该文件很大,因此手动执行任务很麻烦。 如果不可能,我应该使用 scan + for-loop 吗?

现在我只是将所有内容都读取为字符,然后删除不相关的行并将列转换回数字,我认为这不是很节省内存

【问题讨论】:

    标签: string r data-import


    【解决方案1】:

    如果您的文件适合内存,您可以先读取文件,删除不需要的行,然后使用read.csv 读取那些:

    lines <- readLines("yourfile")
    
    # remove unwanted lines: select only lines that do not contain 
    # characters; assuming you have column titles in the first line,
    # you want to add those back again; hence the c(1, sel)
    sel <- grep("[[:alpha:]]", lines, invert=TRUE)
    lines <- lines[c(1,sel)]
    
    # read data from selected lines
    con <- textConnection(lines)
    data <- read.csv(file=con, [other arguments as normal])
    

    【讨论】:

      【解决方案2】:

      如果字符串总是相同的,或者总是包含相同的单词,你可以将它们定义为 NA 值使用

        read.csv(...,  na.strings="")
      

      然后将它们全部删除

      omit.na(dataframe)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多