【问题标题】:Is there a package to process command line options in R?是否有一个包来处理 R 中的命令行选项?
【发布时间】:2010-11-09 18:27:39
【问题描述】:

在 R 中是否有处理命令行选项的包?

我知道commandArgs,但它太基础了。它的结果基本上相当于C 中的argcargv,但我还需要一些东西,就像C++ 中的boost::program_optionsperl 中的GetOptions::Long

特别是,我想提前指定允许哪些选项,并在用户指定其他内容时给出错误消息。

调用将是这样的(使用用户选项 --width=32 --file=foo.txt):

R --vanilla --args --width=32 --file=foo.txt < myscript.R

或者,如果使用Rscript

myscript.R --width=32 --file=foo.txt 

(请不要说“为什么不自己写呢,没那么难”。在其他语言中你也不必自己写。:)

【问题讨论】:

    标签: parsing command-line r options getopt


    【解决方案1】:

    【讨论】:

    • 太棒了!太糟糕了,它不是 R 发行版的一部分(至少不在 R 2.8.1 中)。
    【解决方案2】:

    commandArgs with eval 怎么样?

    test.R

    ## 'trailingOnly=TRUE' means only parse args after '--args'
    args=(commandArgs(trailingOnly=TRUE))
    
    ## Supply default arguments
    if(length(args)==0){
        print("No arguments supplied.")
        ##supply default values
        a = 1
        b = c(1,1,1)
    }else{
        for(i in 1:length(args)){
             eval(parse(text=args[[i]]))
        }
    }
    print(a*2)
    print(b*3)
    

    并调用它

    R CMD BATCH --no-save --no-restore '--args a=1 b=c(2,5,6)' test.R test.out
    

    使用 eval 的常见注意事项当然适用。

    无耻地从这个blog post盗取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-10
      • 2014-06-28
      • 1970-01-01
      • 2014-04-16
      • 2012-11-16
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多