R Script - How to Continue Code Execution on Error

Make execution stop on error in RStudio / Interactive R session

I don't think that there is a way to prevent RStudio from running all the lines, when you select a section and press Ctrl+Enter. Rstudio is just running one line after the other. Even if stopifnot() is called inside of a function, all the lines after that function call will still be evaluated.

If your goal is simply to be informed when something goes wrong, before a lot of code is run in vain, maybe you could define a function similar to stopifnot() that will just go into an endless loop, if there is an error. You could then press Esc or the Stop-Button in RStudio to interrupt the program. Something like this:

waitifnot <- function(cond) {
if (!cond) {
message(deparse(substitute(cond)), " is not TRUE")
while (TRUE) {}
}
}

Now, you can run your example code with this function:

x <- 'test'
waitifnot(is.numeric(x))
print('hello world')

As expected, hello world is never printed. You will get an error message, telling you that something went wrong, and then the program will wait until you abort it manually.

This won't work well in any situation other than interactive mode. To avoid unpleasant situations, you could also let the function react differently, if it is not used in interactive mode, for instance like this:

waitifnot <- function(cond) {
if (!cond) {
msg <- paste(deparse(substitute(cond)), "is not TRUE")
if (interactive()) {
message(msg)
while (TRUE) {}
} else {
stop(msg)
}
}
}

This function will go into an endless loop only if run in interactive mode. Otherwise, it will simply abort execution by calling stop(). I have checked that this works as expected with Ctrl+Enter or the Source button in RStudio (endless loop) and with Rscript on the Bash command line (abort of the program).

Is there any way to have R script continue after receiving error messages instead of halting execution?

See the function try() and it's help page (?try). You wrap your R expression in a try() call and if it succeeds, the resulting object contains, in this case, the fitted model. If it fails, then an object with class "try-error" is returned. This allows you to easily check which models worked and which didn't.

You can do the testing to decide whether to print out the summary for the model or just a failure message, e.g.:

ss107927468.model <- try(aov(Race.5~ss107927468, data=snp1))
if(isTRUE(all.equal(class(ss107927468.model), "try-error"))) {
writeLines("Model failed")
} else {
summary(ss107927468.model)
}

How do I stop/end/halt a script in R?

As far as I could find, there is no single command that really stops a script on every platform/version. There are several ways to handle this:

Put it in a function or curly brackets:

{
if (TRUE) {stop("The value is TRUE, so the script must end here")}

print("Script did NOT end!")
}

OR evaluate the error and handle it like in an if else construction:

if (TRUE) {stop("The value is TRUE, so the script must end here")    
} else { #continue the script
print("Script did NOT end!")
}

OR (EDIT):
Another possibility is to call the script from a seperate 'main' R-scipt, with source("MyScript.R"). Then the script terminates. This however, suppresses all output other then errors to the console.

OR for more complex operations, use tryCatch() as shown here

Is there a way to `source()` and continue after an error?

To make this more concrete, how about the following?

First, to test the approach, create a file (call it "script.R") containing several statements, the first of which will throw an error when evaluated.

## script.R

rnorm("a")
x <- 1:10
y <- 2*x

Then parse it into a expression list, and evaluate each element in turn, wrapping the evaluation inside a call to tryCatch() so that errors won't cause too much damage:

ll <- parse(file = "script.R")

for (i in seq_along(ll)) {
tryCatch(eval(ll[[i]]),
error = function(e) message("Oops! ", as.character(e)))
}
# Oops! Error in rnorm("a"): invalid arguments
#
# Warning message:
# In rnorm("a") : NAs introduced by coercion
x
# [1] 1 2 3 4 5 6 7 8 9 10
y
# [1] 2 4 6 8 10 12 14 16 18 20


Related Topics



Leave a reply



Submit