我编写了一个 R 脚本,其中包含一个用于检索外部(Web)数据的循环。数据的格式大部分时间是相同的,但有时格式会以不可预测的方式发生变化,并且我的循环崩溃(停止运行)。
不管错误如何,有没有办法继续执行代码?我正在寻找类似于 VBA 中的“On error Resume Next”的内容。
先感谢您。
最佳答案
使用 try
或 tryCatch
.
for(i in something)
{
res <- try(expression_to_get_data)
if(inherits(res, "try-error"))
{
#error handling code, maybe just skip this iteration using
next
}
#rest of iteration for case of no error
}
现代方法使用
purrr::possibly
.首先,编写一个获取数据的函数,
get_data()
.然后修改函数,在出错的情况下返回一个默认值。
get_data2 <- possibly(get_data, otherwise = NA)
现在在循环中调用修改后的函数。
for(i in something) {
res <- get_data2(i)
}
关于R 脚本 - 如何在出错时继续执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8852406/