[R] export variable from bash to R

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Mon Oct 29 18:22:39 CET 2012


On Mon, Oct 29, 2012 at 10:43 AM, sophie <melanie.bieli at bluewin.ch> wrote:
> Dear R experts
>
> This probably seems very easy to you guys, but I'm a beginner and would be
> really glad if someone helped me with this:
> I am trying to automate the execution of an R script (let's call it
> "myscript.R") by passing a variable from a bash script to myscript.R.
> I know I can use the command Rscript, but I don't know how to declare in
> bash which variable will be accessed by the "commandArgs" command in
> myscript.R.
>
> So my bash script looks about like this:
>
> #!/bin/bash
>
> VARIABLES=( a b c d )
>
> for i in ${VARIABLES[@]}; do
>         VARIABLENAME=$i
>         Rscript -e 'source("myscript.R")'
> done
>
> In myscript.R, I would like to use the current VARIABLENAME when executing
> the program, i.e.,
> myscript <- function()  {
>
> args <- commandArgs(TRUE)     # args should now be set to either a,b,c, or d
> load(paste("/home/user/../../", args, ".RData", sep=""))    #  this defines
> the path to the data file that will be used in this run
>
> ...further commands...
> }
>
> At the moment, myscript.R doesn't seem to be executed at all when I execute
> the bash script.
> Any help will be greatly appreciated!

 Another replier has already suggested using commandArgs to get extra
arguments on the command line, but if you really want to push bash
variables through to R then you have to export them from bash and get
them using Sys.getenv in R:

$ export VARIABLENAME=a
$ R --slave
Sys.getenv("VARIABLENAME")
[1] "a"

(using R --slave to cut out all the startup messages etc)

Barry




More information about the R-help mailing list