当通过`r BATCH脚本文件`调用时,如何获取当前执行脚本的名称

时间:2013-11-16 01:48:06

标签: r batch-file filepath

我使用

从shell命令行调用脚本
r CMD BATCH myscript.R

我需要在myscript.R中做些什么才能获得带有脚本名称的字符向量(即“myscript.R”)?

注意:

我在类似的主题上发现了很多问题,但找不到任何适合我的内容。特别是问题Determine path of the executing script我得到了修改过的脚本片段:

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

scriptPath始终为空(可能是由于我通过BATCH命令调用脚本的方式)。

2 个答案:

答案 0 :(得分:3)

commandArgs()的一个简单示例适用于我:

myscript.R

commandArgs()[3]

在终端:

R CMD BATCH myscript.R

然后cat myscript.Rout

 commandArgs()[3]
[1] "myscript.R"

答案 1 :(得分:1)

我相信如果您使用Rscript代替R CMD BATCH,它将对您有用。当我试图找出如何将工作目录设置为myscript目录时,我读了同一篇文章。无论如何要运行Rscript

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

这是我的工作目录设置到脚本目录的代码。我一直在尝试不同的替代品,然后我意识到你需要使用Rscript来实现它们的大部分工作。

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