I call a script from a shell command line with
我从shell命令行调用脚本
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")?
在我的脚本里我要做什么。获取带有脚本名称的字符向量(例如。“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).
但是scriptPath总是为空的(可能是因为我通过BATCH命令调用脚本的方式)。
2 个解决方案
#1
3
A simple example with commandArgs()
works fine for me:
突击队()的一个简单示例对我来说很有用:
myscript.R
:
myscript.R:
commandArgs()[3]
in the terminal:
终端:
R CMD BATCH myscript.R
and then cat myscript.Rout
:
然后猫myscript.Rout:
commandArgs()[3]
[1] "myscript.R"
#2
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
我相信如果您使用Rscript而不是rcmd批量,它将为您工作。当我试图弄清楚如何将工作目录设置为myscript的目录时,我读了同一篇文章。无论如何运行Rscript
"....\R-3.0.1\bin\x64\Rscript.exe" Myscript.r > Myscript.r.rout
“.... \ 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.
这是我将工作目录设置为脚本目录的代码。我一直在尝试不同的替代方案,然后我意识到你需要使用Rscript来满足大部分的需求。
args <- commandArgs(trailingOnly = F)
scriptPath <- normalizePath(dirname(sub("^--file=", "", args[grep("^--file=", args)])))
setwd(scriptPath)
#1
3
A simple example with commandArgs()
works fine for me:
突击队()的一个简单示例对我来说很有用:
myscript.R
:
myscript.R:
commandArgs()[3]
in the terminal:
终端:
R CMD BATCH myscript.R
and then cat myscript.Rout
:
然后猫myscript.Rout:
commandArgs()[3]
[1] "myscript.R"
#2
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
我相信如果您使用Rscript而不是rcmd批量,它将为您工作。当我试图弄清楚如何将工作目录设置为myscript的目录时,我读了同一篇文章。无论如何运行Rscript
"....\R-3.0.1\bin\x64\Rscript.exe" Myscript.r > Myscript.r.rout
“.... \ 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.
这是我将工作目录设置为脚本目录的代码。我一直在尝试不同的替代方案,然后我意识到你需要使用Rscript来满足大部分的需求。
args <- commandArgs(trailingOnly = F)
scriptPath <- normalizePath(dirname(sub("^--file=", "", args[grep("^--file=", args)])))
setwd(scriptPath)