[R] writing R shell scripts?

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Jan 24 06:45:13 CET 2007


On Tue, 23 Jan 2007, Deepak Chandra wrote:

> Hi All,
>
> Another newbie question. I want to write an R script that takes
> argument from command line and runs and produces output to stdin.

You will find that difficult: did you mean stdout?

> For example if there is file foo.R with following in it.
>
> args = commandArgs()
> print(args)
>
> then, when I run it like
> $ R foo.R hello
> it should print 'hello' on the terminal.
>
> I searched the mainling list and found a very old post that said said

Please give an exact reference so we know what you are referring to.
This is not what is usually meant by 'R shell scripts' (it is an R script, 
not a shell script).

> that this feature will be implemented soon. I am expecting this has
> already  been implemented by now.

That is not what commandArgs() is documented to do so you will need to do 
something slightly different.  But in the development version of R you can 
come very close:

gannet% cat foo.R
args <- commandArgs(TRUE)
print(args)
gannet% ~/R/R-devel/bin/Rscript foo.R hello
[1] "hello"
gannet%

and in any recent version of R

gannet% cat foo2.R
args <- commandArgs()
m <- match("--args", args)
print(args[-(1:m)])
gannet% R --slave --args hello < foo2.R
[1] "hello"

If you have a platform and build of R for which it works, there is also 
littler (http://biostat.mc.vanderbilt.edu/twiki/bin/view/Main/LittleR), 
but beware that are restrictions not stated on that page (such as the need 
for R built as a shared library, which is not the default).

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list