Is there a package to process command line options in R?

回眸只為那壹抹淺笑 提交于 2019-11-29 21:45:51

问题


Is there a package to process command-line options in R?

I know commandArgs, but it's too basic. Its result is basically the equivalent to argc and argv in C, but I'd need something on top of that, just like boost::program_options in C++, or GetOptions::Long in perl.

In particular, I'd like to specify in advance what options are allowed and give an error message if the user specifies something else.

The call would be like this (with user options --width=32 --file=foo.txt):

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

or, if Rscript is used:

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

(Please don't say, "why don't you write it yourself, it's not that hard". In other languages you don't have to write it yourself either. :)


回答1:


getopt for R




回答2:


How about commandArgs with eval for a built in solution?

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)

and to invoke it

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

The usual caveats w.r.t using eval apply of course.

Shamelessly stolen from this blog post.



来源:https://stackoverflow.com/questions/1110363/is-there-a-package-to-process-command-line-options-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!