【问题标题】:tryCatch - withCallingHandlers - recover from errortryCatch - withCallingHandlers - 从错误中恢复
【发布时间】:2020-04-12 04:33:25
【问题描述】:

我有一个包含一些示例数据的 csv 文件(大约 1000 行)。在使用 read.table 读取 csv 时

  read.table(csv_File,header = FALSE, sep=",",na.strings = '')

我遇到了一个错误,

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

有什么方法可以通过使用 tryCatch 和 withCallingHandlers 来打印此错误消息并继续处理文件的其余部分?

我所期望的只是在出现错误时获取错误消息/堆栈跟踪并处理 csv 中的其余行。

【问题讨论】:

    标签: r


    【解决方案1】:

    不,据我所知,没有办法让read.table 跳过包含错误的行。您应该做的是使用count.fields 函数查找文件的每一行中有多少个字段,然后读取整个文件,删除坏行,然后再次读取。例如:

    fields <- count.fields(csv_File, sep = ",")
    bad <- fields != 5
    lines <- readLines(csv_File)
    
    # At this point you could display the bad lines or
    # give some other information about them.
    
    # Then delete them and read again:
    
    lines <- lines[!bad]
    f <- tempfile()
    writeLines(lines, f)
    read.table(f, header = FALSE, sep=",", na.strings = '')
    unlink(f)
    

    编辑添加:

    我应该提到readr 包在文件包含问题时做得更好。如果你使用

    library(readr)
    read_csv(csv_File, col_names = FALSE)
    

    它将产生一个“tibble”而不是一个数据框,但否则应该做你想做的事。将报告有问题的每一行,并将整体问题与数据集一起保存,以备您以后检查时使用。

    【讨论】:

      猜你喜欢
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 2017-12-06
      • 2012-02-28
      • 1970-01-01
      相关资源
      最近更新 更多