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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With