command-line - 如何从 R 脚本中读取命令行参数?

标签 command-line r parameters

我有一个 R 脚本,我希望能够为其提供几个命令行参数(而不是代码本身中的硬编码参数值)。该脚本在 Windows 上运行。

我找不到有关如何将命令行上提供的参数读取到我的 R 脚本中的信息。如果无法完成,我会感到惊讶,所以也许我只是没有在 Google 搜索中使用最好的关键字...

任何指示或建议?

最佳答案

Dirk's answer here是您需要的一切。这是一个最小的可重现示例。

我做了两个文件:exmpl.batexmpl.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)如果要将命令写入输出文件
  • 在 .R 文件中

    关于command-line - 如何从 R 脚本中读取命令行参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2151212/

    相关文章:

    regex - OSX : change date format in multiple file names

    java - 有没有办法在 Java 中传递方法引用?

    c# - 转换错误

    swift - 从 Silver 命令行在 Windows 上编译 Swift?

    linux - 在终端 (Mac) 中的目录之间复制所有文件

    替换数据帧的非零值

    r - 模拟 t 分布——随机样本

    redirect - Express Node.js框架: How to re-write a URL by replacing one of the named param segments?

    linux - Unix:如何检查数字3从1到1232出现了多少次

    r - 如何在 DT::datatable 中设置多个选项列表和扩展名