如何从 R 脚本中读取命令行参数? [英] How can I read command line parameters from an R script?
问题描述
我有一个 R 脚本,我希望能够为其提供几个命令行参数(而不是在代码本身中硬编码参数值).该脚本在 Windows 上运行.
I've got a R script for which I'd like to be able to supply several command-line parameters (rather than hardcode parameter values in the code itself). The script runs on Windows.
我找不到有关如何将命令行上提供的参数读入我的 R 脚本的信息.如果无法完成,我会感到惊讶,所以也许我只是没有在我的 Google 搜索中使用最好的关键字......
I can't find info on how to read parameters supplied on the command-line into my R script. I'd be surprised if it can't be done, so maybe I'm just not using the best keywords in my Google search...
有什么建议或建议吗?
推荐答案
Dirk's answer here 是您所需要的一切.这是一个最小的可重现示例.
Dirk's answer here is everything you need. Here's a minimal reproducible example.
我制作了两个文件:exmpl.bat
和exmpl.R
.
I made two files: exmpl.bat
and exmpl.R
.
exmpl.bat
:
set R_Script="C:Program FilesR-3.0.2inRScript.exe"
%R_Script% exmpl.R 2010-01-28 example 100 > exmpl.batch 2>&1
或者,使用 Rterm.exe
:
set R_TERM="C:Program FilesR-3.0.2ini386Rterm.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
.结果你会得到:
Save both files in the same directory and start exmpl.bat
. In the result you'll get:
example.png
带有一些情节exmpl.batch
完成所有工作
example.png
with some plotexmpl.batch
with all that was done
你也可以添加一个环境变量%R_Script%
:
You could also add an environment variable %R_Script%
:
"C:Program FilesR-3.0.2inRScript.exe"
并在您的批处理脚本中使用它作为 %R_Script% <filename.r><参数>
and use it in your batch scripts as %R_Script% <filename.r> <arguments>
RScript
和Rterm
的区别:
Rscript
语法更简单Rscript
自动选择 x64 上的架构(参见 R 安装和管理,2.6 子架构 了解详情)Rscript
如果要将命令写入输出文件,则需要 .R 文件中的options(echo=TRUE)
Rscript
has simpler syntaxRscript
automatically chooses architecture on x64 (see R Installation and Administration, 2.6 Sub-architectures for details)Rscript
needsoptions(echo=TRUE)
in the .R file if you want to write the commands to the output file
这篇关于如何从 R 脚本中读取命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!