R脚本 - 如何在出错时继续执行代码

时间:2012-01-13 14:45:43

标签: r

我编写了一个R脚本,其中包含一个检索外部(Web)数据的循环。数据的格式大部分时间都是相同的,但有时格式会以不可预测的方式发生变化,而且我的循环会崩溃(停止运行)。

有没有办法继续执行代码而不管错误?我正在寻找类似于VBA的“On error Resume Next”的内容。

提前谢谢。

3 个答案:

答案 0 :(得分:32)

使用trytryCatch

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)
}

答案 1 :(得分:6)

您可以使用try

# a has not been defined
for(i in 1:3)
{
  if(i==2) try(print(a),silent=TRUE)
  else print(i)
}

答案 2 :(得分:4)

这个相关问题的解决方案如何:

Is there a way to `source()` and continue after an error?

parse(file = "script.R")后跟结果中每个表达式的循环try(eval())

evaluate包。

相关问题