[Rd] R's parsing of command line arguments using commandArgs()
Marc Schwartz (via MN)
mschwartz at mn.rr.com
Mon Sep 26 17:51:00 CEST 2005
On Fri, 2005-09-23 at 15:37 -0500, Marc Schwartz (via MN) wrote:
> Hi all,
>
> I am setting up some R program files for use by our DB programmers to
> enable them to utilize some R functions which will be called from within
> TCL code. R has been installed on an RHEL server and R will process the
> results of SQL queries against an Oracle database.
>
> In some cases, they will generate a data file to be read in and
> processed by R, in others they will simply make the tabulated results
> available.
>
> I know that I could do the SQL queries from within R, however, this is
> the approach that has been defined for now for various reasons.
>
> I wanted to provide some flexibility for them, by passing some of the
> tabulated results via command line arguments to R functions, rather than
> via environment variables, which is easier for them to do in TCL it
> would seem. They would create these values at run time, based upon specs
> that I give them.
>
> Using the following as an example:
>
> $ R --slave --vanilla --args "c(5,5)" "c(.5,.5)" < RScript.R
>
> I can then process "c(5,5)" and "c(.5,.5)" as two arguments, via:
>
> Args <- commandArgs()
>
> where the two arguments are Args[5] and Args[6], respectively. I can
> then of course pass these as "eval(parse(text = Args[5]))" to other R
> functions.
>
>
> However, if there is any whitespace in the two arguments, such as:
>
> R --slave --vanilla --args "c(5, 5)" "c(.5, .5)" < RScript.R
>
> even though surrounded by double quotes (or single quotes or
> backquotes), the two arguments are parsed as four.
>
> Is this behavior expected? I was under the impression, from other C
> based programs and bash shell scripts for example, that the use of the
> double quotes would wrap such text and thus be parsed as a single
> argument.
>
> This is using:
>
> Version 2.1.1 Patched (2005-09-22) on FC4.
Apologies for replying to my own post here, but I wanted to follow up
with a solution provided by Robert McGehee, which works here.
The solution is as follows:
echo "a <- c(5, 5); b <- c(0.5, 0.5)" | cat - RScript.R | R --slave \
--vanilla
This uses echo and cat to pre-pend the 'a' and 'b' vector assignments to
the R program file, before passing the whole thing to R.
This then allows for arguments with embedded whitespace to be passed as
required at run time.
Thanks Robert!
Marc
More information about the R-devel
mailing list