我有一个 R 脚本,我希望能够为其提供几个命令行参数(而不是代码本身中的硬编码参数值)。该脚本在 Windows 上运行。
我找不到有关如何将命令行上提供的参数读取到我的 R 脚本中的信息。如果无法完成,我会感到惊讶,所以也许我只是没有在 Google 搜索中使用最好的关键字...
任何指示或建议?
最佳答案
Dirk's answer here是您需要的一切。这是一个最小的可重现示例。
我做了两个文件:exmpl.bat
和 exmpl.R
.
exmpl.bat
:set R_Script="C:\Program Files\R-3.0.2\bin\RScript.exe"
%R_Script% exmpl.R 2010-01-28 example 100 > exmpl.batch 2>&1
或者,使用
Rterm.exe
:set R_TERM="C:\Program Files\R-3.0.2\bin\i386\Rterm.exe"
%R_TERM% --no-restore --no-save --args 2010-01-28 example 100 < exmpl.R > exmpl.batch 2>&1
exmpl.R
:options(echo=TRUE) # if you want see commands in output file
args <- commandArgs(trailingOnly = TRUE)
print(args)
# trailingOnly=TRUE means that only your arguments are returned, check:
# print(commandArgs(trailingOnly=FALSE))
start_date <- as.Date(args[1])
name <- args[2]
n <- as.integer(args[3])
rm(args)
# Some computations:
x <- rnorm(n)
png(paste(name,".png",sep=""))
plot(start_date+(1L:n), x)
dev.off()
summary(x)
将两个文件保存在同一目录中并启动
exmpl.bat
.在结果中你会得到:example.png
有一些情节exmpl.batch
完成所有工作 您还可以添加环境变量
%R_Script%
:"C:\Program Files\R-3.0.2\bin\RScript.exe"
并在您的批处理脚本中使用它作为
%R_Script% <filename.r> <arguments>
RScript
之间的差异和 Rterm
:Rscript
具有更简单的语法 Rscript
自动选择 x64 上的体系结构(有关详细信息,请参阅 R Installation and Administration, 2.6 Sub-architectures)Rscript
需求options(echo=TRUE)
如果要将命令写入输出文件 关于command-line - 如何从 R 脚本中读取命令行参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2151212/