How do I debug Rscripts
that are run from the command line?
I am currently using the getopt
package to pass command line options, nut when the
I either use old-school print statements, or interactive analysis. For that, I first save state using save()
, and then load that into an interactive session (for which I use Emacs/ESS). That allows for interactive work using the script code on a line-by-line basis.
But I often write/test/debug the code in interactive mode first before I deploy in a littler script.
You could pass your command line arguments into an interactive shell with --args and then source('') the script.
$ R --args -v
R version 2.8.1 (2008-12-22)
Copyright (C) 2008 The R Foundation for Statistical Computing
ISBN 3-900051-07-0
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> require(getopt)
Loading required package: getopt
> opt = getopt(c(
+ 'verbose', 'v', 2, "integer"
+ ));
> opt
$verbose
[1] 1
> source('my_script.R')
You could now use the old browser() function to debug.
Another option is to work with the options(error) functionality. Here's a simple example:
options(error = quote({dump.frames(to.file=TRUE); q()}))
You can create as elaborate a script as you want on an error condition, so you should just decide what information you need for debugging.
Otherwise, if there are specific areas you're concerned about (e.g. connecting to a database), then wrap them in a tryCatch() function.