r - 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 中的其余行。
解决方案
不,据我所知,没有办法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”而不是一个数据框,但否则应该做你想做的事。将报告有问题的每一行,并将整体问题与数据集一起保存,以备您以后检查时使用。
推荐阅读
- reactjs - React Quill - 如何显示两个文本版本之间的差异?
- makefile - `make` 不会自动链接本地安装的库(CS50x 的 cs50.h)
- python - 在 pandas 中获取每个组的分布的 df
- javascript - Leaflet - 即使在删除事件侦听器后,标记也不会停止移动
- ruby-on-rails - 渲染集合 [where(store: current_user).each do] ?如何从渲染加载特定数据
- c++ - 获取多处理器的 Windows CPU 利用率的正确方法
- python-3.8 - 在 while 循环中写入 plt.show() 行后,如何成功输入输入?
- r - 在R中的数据框中随机交换两个不同列中的一定数量的条目
- json - VBA解析JSON空数据
- python - 升级自制软件 ocrmypdf 致命 Python 错误后:config_get_locale_encoding: failed to get the locale encoding: nl_langinfo