[R] reading file names for R batch process

Duncan Temple Lang duncan at research.bell-labs.com
Thu Dec 6 18:04:16 CET 2001

Thomas Lumley wrote:
> On Thu, 6 Dec 2001, Sven Garbade wrote:
> > Prof Brian D Ripley wrote:
> > >
> > > On Thu, 6 Dec 2001, Sven Garbade wrote:
> > >
> > > > Hi all,
> > > >
> > > > I've written a function that takes several filenames as arguments, does
> > > > some calculations and write new files. Now I want to write a shell
> > > > script (under Linux) that determines the files for the R process and
> > > > starts R with the filenames as arguments. But how can I commit the
> > > > filenames to the R process?
> > >
> > > via enviroment variables, most easily.
> > >
> > > Read by Sys.getenv.
> >
> > Ah, this is very easy and works! Thanks, Sven
> I believe you could also use the commandArgs() function.
> 	-thomas

Using commandArgs() would, in theory, be both a better and simpler
mechanism. It doesn't require you to come up with names for the
environment variables and agree on those in both the shell script and
the R code.  Additionally, the values will not be passed on to any
applications run from within the R session and so avoid any potential
conflicts between the use of environment variables by different

For your application, since file names are typically single words,
this should work.

  echo 'print(commandArgs())' | R --save file1 file2

However, the way the R script is set up at present, the commandArgs()
doesn't work in general, at least with the obvious usage. For example,

  echo 'print(commandArgs())' | R --save 'my first argument' argument2
ARGUMENT 'my' __ignored__
ARGUMENT 'first' __ignored__
ARGUMENT 'argument' __ignored__
ARGUMENT 'argument2' __ignored__
[1] "/home3/duncan/R/R-cvs/bin/R.bin" "--slave"
[3] "my"                              "first"
[5] "argument"                        "argument2"

So we get warning messages from the R executable (not script) and also
it breaks the single argument 'my first argument' into 3 distinct arguments.

In the future, this might be fixed by a) using a -- separator for
arguments that leaves anything past that uninterpreted by R.
and b) preserving the quotes around arguments.

So a command like
  echo 'print(commandArgs())' | R --save -- 'my first argument' argument2
would print 
[1] "/home3/duncan/R/R-cvs/bin/R.bin" "--slave"
[3] "my first argument"               "argument2"

But that will have to wait.



Duncan Temple Lang                duncan at research.bell-labs.com
Bell Labs, Lucent Technologies    office: (908)582-3217
700 Mountain Avenue, Room 2C-259  fax:    (908)582-3340
Murray Hill, NJ  07974-2070       
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list