views:

69

answers:

1

I have written a shebang R script and would like to execute it from a Perl script. I currently use system ($my_r_script_path, $r_script_arg1, $r_script_arg2, ...) and my question is how can I verify the R script terminates normally (no errors or warnings).

guess I should make my R script return some true value at the end, only if everything is OK, then catch this value in Perl, but I'm not sure how to do that.

Thanks!

+2  A: 

You can set the return value in the command quit(), eg q(status=1). Default is 0, see also ?quit. How to catch that one in Perl, is like catching any other returning value in Perl. It is saved in a special variable $? if I remember right. See also the examples in the perldoc for system, it should be illustrated there.

On a sidenote, I'd just use the R-Perl interface. You can find info and examples here : http://www.omegahat.org/RSPerl/

Just for completeness :

At the beginning of your script, you can put something like :

options(
    warn=2, # This will change all warnings into errors,
            # so warnings will also be handled like errors
    error= quote({
      sink(file="error.txt"); # save the error message in a file
      dump.frames();
      print(attr(last.dump,"error.message"));
      sink();
      q("no",status=1,FALSE) # standard way for R to end after errors
    })
)

This will save the error message, and break out of the R session without saving, with exit code 1 and without running the .Last.

Still, the R-Perl interface offers a lot more possibilities that are worth checking out if you're going to do this more often.

Joris Meys
And how can I tell at the end of the script if everything went OK (including no warnings)? Do I have to set some try block around each command that might fail? Or is there some global way to terminate immediately on any error/warning and return some value?
David B
use the error options for that. You can specify any function you want when an error occurs, as I illustrated before. You can also make any warning being an error by using options(warn=2). see also http://stackoverflow.com/questions/3650444/r-script-line-numbers-at-error/3660847#3660847
Joris Meys
Thanks for the "completeness " (+1)
David B