首页 > 解决方案 > tryCatch - withCallingHandlers - 从错误中恢复

问题描述

我有一个包含一些示例数据的 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

解决方案


不,据我所知,没有办法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”而不是一个数据框,但否则应该做你想做的事。将报告有问题的每一行,并将整体问题与数据集一起保存,以备您以后检查时使用。


推荐阅读