![](/img/trans.png)
[英]Is there a way to continue a for loop in R after an error without using try() or tryCatch()
[英]Continue for loop in R after error (example using vector of numbers and letters)
我目前正在一个项目中尝试在for循环中完成一项任务。 有很多地方可能出问题(涉及通过rmarkdown创建pdf报告),但是在这种情况下,我不在乎是否出了问题,我只是希望for循环继续进行。
在下面的玩具示例中,我希望能够打印数字2到16,同时跳过字母“ a”。
something<-function(x){
print(x + 1)
}
for(i in c(1:10,'a',11:15))
{
res <- try(something(i))
if(inherits(res, "try-error"))
{
#error handling code, maybe just skip this iteration using
next
}
#rest of iteration for case of no error
}
大致基于以下答案中提供的示例。
我尝试过修改其他几个“如何在R中继续for循环”以至于没有成功。
我不是一个全职程序员,所以我确信我缺少一些非常简单的东西,但是可以提供任何帮助。
我有一个类似的问题,我有一个函数在for
循环中运行,如果error
,则需要它保持运行。 这是我的操作方式:
OutputStorage=list()
for (i in 1:k){
Output=tryCatch(examplefunction(x), error=function(e) NULL)
OutputStorage[[i]]=Output
}
因此,如果有输出,则将其存储在list
;如果没有,则为此存储NULL
。 我认为它正在运行; 实际上刚刚运行它。 希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.