我已经编写了一个R脚本,其中包含一个用于检索外部(web)数据的循环。数据的格式大部分时间是相同的,但是有时格式会以不可预测的方式改变,我的循环会崩溃(停止运行)。
有没有一种方法可以在出现错误的情况下继续执行代码?我正在寻找类似于“错误恢复下一步”从VBA。
提前谢谢你。
发布于 2012-01-13 22:58:47
使用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)
}发布于 2012-01-13 22:58:30
您可以使用try
# a has not been defined
for(i in 1:3)
{
  if(i==2) try(print(a),silent=TRUE)
  else print(i)
}发布于 2013-01-31 05:55:44
关于这个相关问题的解决方案如何:
Is there a way to source() and continue after an error?
在结果中的每个表达式上,要么使用parse(file = "script.R"),后面跟着一个循环的try(eval())。
或者evaluate包。
https://stackoverflow.com/questions/8852406
复制相似问题