Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R continue loop on error

Tags:

r

apparently try and trycatch do not work for this problem! Any alternative solutions?

i'm trying to make the following example code work without actually changing any code

result = 0
for(i in 1:10){
  result = result + i
  log("a") #I do not care about this error
  result = result + i
}

This should give result = 110

If i actually do it manually by copying the part inside the loop and increasing the counter it works perfectly:

result = 0

#iteration 1
i = 1
result = result + i
log("a")
result = result + i

#iteration 2
i = i+1
result = result + i
log("a")
result = result + i

#iteration 3
i = i+1
result = result + i
log("a")
result = result + i

#etc.

However my real code has about 1000 lines and needs to loop a few hundred times.

So i'd like to have some option

options(on.error.just.continue.the.next.line) = TRUE

I've read about try/tryCatch but I don't understand it correctly I think

like image 711
Ivo Avatar asked Aug 04 '16 13:08

Ivo


1 Answers

If you just want the code to run, you can use try instead:

result <- 0
for(i in 1:10){
  result = result + i
  try({log("a")}) #I do not care about this error
  result = result + i
}

Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function

result
[1] 110

To turn off the message, use

try({log("a")}, silent=TRUE)

If you are worried about a larger block of code, you can wrap it in { } as follows:

result <- 0
for(i in 1:10){
  try({                # start code block
  result = result + i
  log("a")             # I do not care about this error
  result = result + i
  }, silent=TRUE)      # end of try function
}

result
[1] 55

Here, the first assignment to result completes in the for loop. Then the error occurs which "wipes out" the execution of the rest of the code block, which is the second assignment here. However, the loop execution is allowed to continue through completion.

like image 199
lmo Avatar answered Nov 14 '22 21:11

lmo