我通常在Python中使用argparse,而在R中使用docopt。我尚未从argparse中错过的我尚未在docopt中弄清楚的功能之一就是能够为每个参数指定所需的数据类型。例如,在argparse中,我需要使用

parser.add_argument("square", help="display a square of a given number",
                type=int)


在docopt / R中,我在文档中找不到有关要求特定数据类型的任何内容。

-s <square>, --square=<square>   display a square of a given number #additional option to require integer input?


Python版本的docopt GitHub存储库上有一个封闭的issue,似乎表明这不是基本docopt的一部分,并提供了Python解决方案,但这不适用于R。任何人都可以提出任何建议/ R中使用docopt验证参数输入的更优雅的方法?

最佳答案

不知道这是否足够优雅,因为它涉及设置默认值,然后使用utils::type.convert确定class / typeof

"Usage: my_program.R [-hson FILE] [--quiet | --verbose] [INPUT ...]

-h --help        show this
-s --sorted      sorted output
--coefficient=K  [default: 2.95] The K coefficient
--numSim=K       [default: 200] number of simulations
--output=FILE    [default: test.txt] Output file
--directory=DIR  [default: ./] Some directory
-o FILE          specify output file [default: ./test.txt]
--quiet          print less text
--verbose        print more text" -> doc
opts <- docopt(doc, "-s --quiet")
str(opts)

newopts <- lapply(opts, function(x) utils::type.convert(as.character(x),as.is=T))
(definedClasses <- unlist(lapply(newopts, typeof)))


在运行程序时,可以根据此definedClasses测试输入。

您可能还想检出getoptoptparse / argparse软件包,并在Parsing command line arguments in R scripts

参考文献:

http://docopt.org

http://rgrannell1.github.io/blog/2014/08/04/command-line-interfaces-in-r

http://docopt.readthedocs.org/en/0.2.0/

关于python - docopt-为每个参数要求特定的数据类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36700879/

10-12 20:40