3

I call a script from a shell command line with

r CMD BATCH myscript.R

What do I have to do in myscript.R to get a character vector with the name of the script (i.e. "myscript.R")?

Note:

I found numerous questions on similar topics, but couldn't find anything that work for me. Particularly from question Determine path of the executing script I got the modified script snippet:

args <- commandArgs(trailingOnly = F)  
scriptPath <- sub("^--file=", "", args[grep("^--file=", args)])

but scriptPath is always empty (probably due to the way I call the script via the BATCH command).

Community
  • 1
  • 1
halloleo
  • 9,216
  • 13
  • 64
  • 122

2 Answers2

3

A simple example with commandArgs() works fine for me:

myscript.R:

commandArgs()[3]

in the terminal:

R CMD BATCH myscript.R

and then cat myscript.Rout:

 commandArgs()[3]
[1] "myscript.R"
user1981275
  • 13,002
  • 8
  • 72
  • 101
1

I believe if you use Rscript instead of R CMD BATCH it will work for you. I read the same post when I was trying to figure out how set working directory to directory of myscript. Anyway to run Rscript

"....\R-3.0.1\bin\x64\Rscript.exe" Myscript.r > Myscript.r.rout

And here is my code to set working directory to directory of script. I kept trying different alternatives to this then I realized you need to be using Rscript for the bulk of them to work.

args <- commandArgs(trailingOnly = F)  
scriptPath <- normalizePath(dirname(sub("^--file=", "", args[grep("^--file=", args)])))
setwd(scriptPath)
CCurtis
  • 1,770
  • 3
  • 15
  • 25