![](/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.