[R] Rscript example

Petr Savicky savicky at cs.cas.cz
Fri Mar 2 09:37:11 CET 2012


On Thu, Mar 01, 2012 at 11:18:33PM -0800, statquant2 wrote:
> Hey Petr,
> ok I was thinking that R would handle the split by itself.
> I guess using eval we can even make arg1=val1 being executed by R.

Hi.

For executing the assignments, try myRscript.R containing

  args <- commandArgs(TRUE);
  argmat <- sapply(strsplit(args, "="), identity)
 
  for (i in seq.int(length=ncol(argmat))) {
      assign(argmat[1, i], argmat[2, i])
  }

  # available variables
  print(ls()) 

  # print variables arg1, arg2, arg3
  print(arg1)
  print(arg2)
  print(arg3)

Then the command line

  ./myRscript.R arg1=aa arg2=22 arg3=cc

yields

  [1] "argmat" "args"   "arg1"   "arg2"   "arg3"   "i"     
  [1] "aa"
  [1] "22"
  [1] "cc"

Another option for setting some variables before executing an R script
is to have two scripts, a shell script and an R script, containing

shell script "callR.sh"

  #!/bin/bash
  
  <PATH_TO_R>/bin/R --vanilla << EEE
  args <- c("$2","$3","$4","$5")
  source("$1")
  EEE

a trivial R script "tst.R"

  print(args)

Then,

  ./callR.sh tst.R aa 22 cc

leads to

  ...
  ...
  Type 'demo()' for some demos, 'help()' for on-line help, or
  'help.start()' for an HTML browser interface to help.
  Type 'q()' to quit R.
  
  > args <- c("aa","22","cc","")
  > source("tst.R")
  [1] "aa" "22" "cc" ""  
  > 

Hope this helps.

Petr Savicky.



More information about the R-help mailing list