如何从 R 脚本读取命令行参数? [英] How can I read command line parameters from an R script?

查看:36
本文介绍了如何从 R 脚本读取命令行参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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 is everything you need. Here's a minimal reproducible example.

我制作了两个文件:exmpl.batexmpl.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 plot
    • exmpl.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% ;<参数>

    and use it in your batch scripts as %R_Script% <filename.r> <arguments>

    RScriptRterm 的区别:

    • Rscript 语法更简单
    • Rscript 自动选择 x64 上的架构(参见 R 安装和管理,2.6 子架构 详情)
    • Rscript 如果要将命令写入输出文件,则需要 .R 文件中的 options(echo=TRUE)
    • Rscript has simpler syntax
    • Rscript automatically chooses architecture on x64 (see R Installation and Administration, 2.6 Sub-architectures for details)
    • Rscript needs options(echo=TRUE) in the .R file if you want to write the commands to the output file

    这篇关于如何从 R 脚本读取命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆