1

here is my problem:

I am using a loop to run a function over a list of objects. Most of the objects work fine and produce the desired output. However, some others produce an error and when this happens, the loop stops running.

I am trying to find a way in which, every time the loop finds an object that gives an error, the loop ignores the problematic object and goes to the next object. So the loop can run until the end of the entire list, only producing the outputs of the object that worked fine.

I am implementing the loop like this:

for(i in n:m){
   myfunction
}

thank you!

juba
  • 47,631
  • 14
  • 113
  • 118
user18441
  • 643
  • 1
  • 7
  • 15

2 Answers2

2

Just wrap what may fail with a try()

for(i in n:m){
out[[i]] = try( myfunction )

}  
  out

probably better would be to put the try() within myfunction(). But I don't know what that function entails. Sometimes a good strategy is to preassign your output to NAs, then at the beginning of your for loop ask:

 if("conditionwherefunctionfails") i = i+1

that will just skip that iteration and continue your loop.

Seth
  • 4,745
  • 23
  • 27
1

Very little to go on, but you simply need an if statement to recognise the troublesome object, and do nothing, otherwise execute your function:

for(i in n:m){
    if ( i != ... ) { //replace ... with NaN or null, or whatever is causing the error
        myfunction(i)
    }
}

With the limited information, I cannot tell you what should be in the place of ...

mjshaw
  • 401
  • 2
  • 7