Search code examples
revaluatecranrscript

Set value of --args from within R session


I would like to use the evaluate package to simulate executing (lots of) r-scripts while recording the outputs using evaluate. Evaluate is designed to do exactly this and it works almost out of the box. However, when using Rscript, the user passes arguments via the command line --args which are retrieved in R using the base::commandArgs function.

Is there any sensible way I can override the value of --args from within a running R session such that an R script using base::commandArgs() would work as expected without having to modify the script itself?


Solution

  • I had a delve into R's guts and came up with some smelly intestines to play with.

    The command line is copied from C's argc/argv into a global C variable with this function in the source code:

    void R_set_command_line_arguments(int argc, char **argv)
    

    So we need a little C wrapper to get round the fact that the first parameter isn't a pointer:

    #include "R.h"
    #include "R_ext/RStartup.h"
    void set_command(int *pargc, char **argv){
      R_set_command_line_arguments(*pargc, argv);
    }
    

    compile in the usual way:

    R CMD SHLIB setit.c
    

    load, call:

    > dyn.load("setit.so")
    > commandArgs()
    [1] "/usr/lib/R/bin/exec/R"
    > invisible(.C("set_command",as.integer(2),c("Foo","Bar")))
    > commandArgs()
    [1] "Foo" "Bar"
    

    from then on commandArgs() will return that vector until you change it.