Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

debugging littler/Rscripts

Tags:

r

debugging

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 there's a bug, it is hard for me to:

  1. see what exactly went wrong;
  2. debug interactively in R (since the script expects command line options.)

Does anyone have example code and willing to share?

like image 986
Eduardo Leoni Avatar asked Oct 26 '09 02:10

Eduardo Leoni


3 Answers

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.

like image 111
Mark Avatar answered Nov 18 '22 06:11

Mark


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.

like image 4
Dirk Eddelbuettel Avatar answered Nov 18 '22 07:11

Dirk Eddelbuettel


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.

like image 3
Shane Avatar answered Nov 18 '22 06:11

Shane