I have a large R script of, say, 142 small sections. If one section fails with an error I\'d like the script to continue rather than halt. The sections don\'t necessarily de
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