[R] Rscript example

Petr Savicky savicky at cs.cas.cz
Thu Mar 1 22:24:34 CET 2012


On Thu, Mar 01, 2012 at 11:53:00AM -0800, statquant2 wrote:
> Hi there,
> I am trying to find an example how to use Rscript
> Let's suppose I want to pass 3 arguments (I don't want [options] and -e
> [expressions] as described in help) 
> 
> *on the command line
> myRscript.R -arg1=value1 -arg2=value2 -arg3=value3
> 
> *In the script
> #! /path/to/Rscript
> args = commandArgs(TRUE);
> 
> >From what I see args is just a string, do I do things correctly ?

Hi.

Extending your example with print(args), i obtained

  ./myRscript.R -arg1=value1 -arg2=value2 -arg3=value3
  [1] "-arg1=value1" "-arg2=value2" "-arg3=value3"

If you can use a fixed order of the arguments, then you
need not use the "-arg[i]=" parts. The arguments are
strings on the command line, so they are also passed
to R as strings, but you can convert them inside the
script. For example, with the above script, i get

  ./myRscript.R 23 45 78
  [1] "23" "45" "78"

However, if the script contains

   args <- as.numeric(args)

, then i get

  ./myRscript.R 23 45 78
  [1] 23 45 78

which is a numeric vector.

If you want to keep the "arg[i]=" structure, you can have in
the script

  x <- strsplit(args, "=")
  print(x)

and a call produces

  ./myRscript.R -arg1=value1 -arg2=value2 -arg3=value3
  [[1]]
  [1] "-arg1"  "value1"
  
  [[2]]
  [1] "-arg2"  "value2"
  
  [[3]]
  [1] "-arg3"  "value3"

The list "x" may then be further analyzed.

Hope this helps.

Petr Savicky.



More information about the R-help mailing list