Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Script - How to Continue Code Execution on Error

Tags:

r

I have written an R script which includes a loop that retrieves external (web) data. The format of the data are most of the time the same, however sometimes the format changes in an unpredictable way and my loop is crashing (stops running).

Is there a way to continue code execution regardless the error? I am looking for something similar to "On error Resume Next" from VBA.

Thank you in advance.

like image 420
Financial Economist Avatar asked Jan 13 '12 14:01

Financial Economist


People also ask

How do I continue a loop if error in R?

By default, try will continue the loop even if there's an error, but will still show the error message. We can supress the error messages by using silent = TRUE .

How do you fix an error in R?

Condition Handling in Rtry(): it helps us to continue with the execution of the program even when an error occurs. tryCatch(): it helps to handle the conditions and control what happens based on the conditions.

How do I ignore an error in R?

The simplest way of handling conditions in R is to simply ignore them: Ignore errors with try() . Ignore warnings with suppressWarnings() .

What does R code execution error mean?

The error arises when the package cannot be decompressed by R correctly. Below can be possible solutions: Try restarting your R session (e.g. .


2 Answers

Use try or tryCatch.

for(i in something) {   res <- try(expression_to_get_data)   if(inherits(res, "try-error"))   {     #error handling code, maybe just skip this iteration using     next   }   #rest of iteration for case of no error } 

The modern way to do this uses purrr::possibly.

First, write a function that gets your data, get_data().

Then modify the function to return a default value in the case of an error.

get_data2 <- possibly(get_data, otherwise = NA) 

Now call the modified function in the loop.

for(i in something) {   res <- get_data2(i) } 
like image 189
Richie Cotton Avatar answered Sep 24 '22 23:09

Richie Cotton


You can use try:

# a has not been defined for(i in 1:3) {   if(i==2) try(print(a),silent=TRUE)   else print(i) } 
like image 29
MånsT Avatar answered Sep 26 '22 23:09

MånsT