Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retry for-loop R loop if error

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)

like image 906
Ron Crash Avatar asked Aug 13 '15 23:08

Ron Crash


People also ask

How to handle an error in r loop?

One of the easier ways is to ignore them and continue moving through the loop. This is accomplished with the try function which simply wraps around the entire body of the loop. By default, try will continue the loop even if there's an error, but will still show the error message.

How to ignore errors in a loop?

Re: How do I ignore errors and let the loop continue while executing a loop in JSL? The easiest way to handle this is to use the Try() function. It allows you to return a value if the statement(s) within the Try() function have an error. You can then detect the error and handle it the way it needs to be handled.

How do I stop a loop from running in R?

A break statement is used inside a loop (repeat, for, while) to stop the iterations and flow the control outside of the loop.

How does a loop work in R?

If we want a set of operations to be repeated several times we use what's known as a loop. When you create a loop, R will execute the instructions in the loop a specified number of times or until a specified condition is met. There are three main types of loop in R: the for loop, the while loop and the repeat loop.


1 Answers

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.

like image 78
philchalmers Avatar answered Oct 11 '22 14:10

philchalmers