Non-catastrophic error handling in R batch mode

Sep 22, 2015 · 237 words · 2 minutes read R

R batch processing is a way to run R scripts non-interactively from the commandline. This is especially useful when you want to generate a log file but don’t need the (minimal) overhead of R Markdown – or the major overhead of Sweave/knitr.

Running a script in batch mode is easy but doesn’t have very good error handling behavior. By this I mean that if R encounters an error, it will be written to the file and R will quit with exit status 1 (non-catastrophic failure). However this does not necessarily give much information – depending on how decipherable the error message is.

Here is the basic syntax for running a R script non-interactively in batch mode. This will execute script.R without saving or restoring any session data files. The --vanilla option is similar but will prevent reading the Rprofile.site or .Rprofile files. Output, including warnings and errors, is automatically redirected to the output.log file.

\$ R CMD BATCH --no-save --no-restore script.R output.log


Since I don’t like the default error handing behavior, the trick is to modify the .Rprofile. In this example I set a conditional statement so that when R is running non-interactively and encounters an error it will print the session information and then exit (with status 1). This can easily be modified to provide additional behaviors (e.g. list objects, their structures, etc.) when R encounters an error.

if (!interactive()){
options(error = quote({print(utils::sessionInfo()); q(status = 1)}))
}