tags:

views:

54

answers:

2

I would like to run a sequence of R scripts from the bash command line. Can I keep the R session 'open' between calls? Or do I have to save and load objects and re-load the libraries in each script?

Thanks in advance

+5  A: 

If you mean separate

R CMD BATCH foo.R
R CMD BATCH bar.R

then yes, you would have to arrange for anything required by foo.R to be loaded during execution of foo.R and the same for bar.R. If, for example, foo.R computes something for use in bar.R, why not have a master script foobar.R that contains:

## Load required packages
require(pkg1)
require(pkg2)

## Run FOO script to generate objects FOO and foo
source(foo.R)
## Run BAR script to process objects FOO and foo
source(bar.R)

and run that one master script through R CMD

R CMD BATCH foobar.R

HTH

Gavin Simpson
Thanks for your quick answer. The main reason is that foo and bar will be in different 'modules' of a workflow, and I want to keep them separate so that I could have one script that runs foo.R and then bar.R and another that runs foo.R and then bar2.R, or foo2.R and then bar.R and etc.
David
+1  A: 

Read ?Renviron this explains. There are a few options.

  1. save a .First function in the environment file .RData that loads the packages with options(defaultPackages)
  2. Set R_DEFAULT_PACKAGES as an environment variable through the command or through .REnviron file.
  3. Just load the packages in each script, this is by far the easiest and the easiest to understand.

If you mean more than just libraries save the environment at the end of each run and make sure it loads for the next script.

Andrew Redd