简体   繁体   中英

How do I get in R the name of currently executed script when called via `r BATCH script file`

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 (ie "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).

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"

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM