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

Fin*_*ist 31 r

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

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

先感谢您.

Ric*_*ton 36

使用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
}
Run Code Online (Sandbox Code Playgroud)

现代的方法是使用它purrr::possibly.

首先,编写一个获取数据的函数get_data().

然后修改函数以在出错时返回默认值.

get_data2 <- possibly(get_data, otherwise = NA)
Run Code Online (Sandbox Code Playgroud)

现在在循环中调用修改后的函数.

for(i in something) {
  res <- get_data2(i)
}
Run Code Online (Sandbox Code Playgroud)

  • 在我看来,使用 tryCatch 而不是 try,更简洁的语法和更多的控制。 (2认同)

Mån*_*nsT 7

你可以使用try:

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


Mat*_*wle 5

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

有没有办法“source()”并在出错后继续?

无论parse(file = "script.R")后跟一个loop'dtry(eval())上结果中的每个表达式。

或者evaluate包裹。