我使用
从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命令调用脚本的方式)。
答案 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)