Retry for-loop R loop if error

删除回忆录丶 提交于 2019-12-12 07:21:47

问题


I have an R For loop that downloads data from a server and adds result to table however, I sometimes get an error stopping the loop. If I tell it to redo the last download and continue, it works for another while before the next error. The error isn't with code or data, but is random; sometimes it runs for 2.5 hours, other times it stops after 45 minutes downloading the same data.
Is there a way I could get my loop to take a step back if there is an error and retry? eg. in

for (i in 1:1000){
    table[i,] <- downloadfnc("URL", file = i)
}

lets say I get an error while it was downloading i=500, all I do to fix is:

for (i in 500:1000){
    i <- i + 499     #since i starts at 1, 499+1=500
    table[i,] <- downloadfnc("URL",file = i)
}

then it downloads file"500" even though it got an error last time. is there a way I could automate it, so that if there is an error, it takes a step back (i-1) and retry it (perhaps with a few seconds delay)?

(been using R for only several weeks, so basic talk please)


回答1:


You could throw a try-catch combo.

for (i in 1:1000){
    while(TRUE){
       df <- try(downloadfnc("URL", file = i), silent=TRUE)
       if(!is(df, 'try-error')) break
    }
    table[i,] <- df
}

This will continue within the while loop until the file is successfully downloaded, and only move on when it is successfully downloaded.



来源:https://stackoverflow.com/questions/31999808/retry-for-loop-r-loop-if-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!