1

我通常在 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 repo 上有一个已关闭的问题,似乎表明这不是基本 docopt 的一部分,并为 Python 提供了解决方案,但这并不直接适用于 R。任何人都可以提供任何建议/更优雅在 R 中使用 docopt 验证参数输入的方法?

4

2 回答 2

1

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

"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)))

当您运行程序时,您可以针对 this 测试输入definedClasses

您可能还想查看getoptand optparse/argparse包以及此 SO post Parsing command line arguments in R scripts

参考:

http://docopt.org

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

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

于 2016-04-19T07:50:44.497 回答
-1

我有点好奇为什么你不使用docoptpython 或者你为什么不在 R 中使用argparse(或optparse)?

如果您想知道这是如何使用optparseR 包执行您请求的功能:

> library("optparse")
> parser = OptionParser()
> parser = add_option(parser, c("-s", "--square"), 
+    type="integer", 
+    help="display a square of a given number")
> typeof(parse_args(parser, "--square=5")$square)
[1] "integer"

如何使用argparse包执行此操作(后一个具有 python 依赖项):

> parser = argparse::ArgumentParser()
> parser$add_argument("-s", "--square", 
+    type="integer",
+    help="display a square of a given number")
> typeof(parser$parse_args("--square=5")$square)
[1] "integer"
于 2018-11-30T00:37:33.293 回答