by0*_*by0 3 command-line arguments r optparse argparse
我试图通过命令行将多个文件路径参数传递给Rscript,然后可以使用参数解析器进行处理.最终我会想要这样的东西
Rscript test.R --inputfiles fileA.txt fileB.txt fileC.txt --printvar yes --size 10 --anotheroption helloworld -- etc...
Run Code Online (Sandbox Code Playgroud)
通过命令行传递,并在解析时将结果作为R中的数组
args$inputfiles = "fileA.txt", "fileB.txt", "fileC.txt"
Run Code Online (Sandbox Code Playgroud)
我尝试了几种解析器,包括optparse和getopt,但它们似乎都不支持这种功能.我知道argparse确实如此,但它目前不适用于R版本2.15.2
有任何想法吗?
谢谢
虽然在问这个问题时它没有在CRAN上发布,但argparse模块的测试版现在已经可以实现了.它基本上是一个相同名称的流行python模块的包装器,因此您需要安装最新版本的python才能使用它.有关详细信息,请参阅安装说明 基本示例包括一个任意长的数字列表,这些数字应该不难修改,因此您可以获取任意长的输入文件列表.
> install.packages("argparse")
> library("argparse")
> example("ArgumentParser")
Run Code Online (Sandbox Code Playgroud)
您描述命令行选项的方式与大多数人期望使用它们的方式不同。通常,命令行选项将采用单个参数,而没有前面选项的参数作为参数传递。如果一个参数需要多个项目(如文件列表),我建议使用 strsplit() 解析字符串。
这是一个使用 optparse 的示例:
library (optparse)
option_list <- list ( make_option (c("-f","--filelist"),default="blah.txt",
help="comma separated list of files (default %default)")
)
parser <-OptionParser(option_list=option_list)
arguments <- parse_args (parser, positional_arguments=TRUE)
opt <- arguments$options
args <- arguments$args
myfilelist <- strsplit(opt$filelist, ",")
print (myfilelist)
print (args)
Run Code Online (Sandbox Code Playgroud)
以下是几个示例运行:
$ Rscript blah.r -h
Usage: blah.r [options]
Options:
-f FILELIST, --filelist=FILELIST
comma separated list of files (default blah.txt)
-h, --help
Show this help message and exit
$ Rscript blah.r -f hello.txt
[[1]]
[1] "hello.txt"
character(0)
$ Rscript blah.r -f hello.txt world.txt
[[1]]
[1] "hello.txt"
[1] "world.txt"
$ Rscript blah.r -f hello.txt,world.txt another_argument and_another
[[1]]
[1] "hello.txt" "world.txt"
[1] "another_argument" "and_another"
$ Rscript blah.r an_argument -f hello.txt,world.txt,blah another_argument and_another
[[1]]
[1] "hello.txt" "world.txt" "blah"
[1] "an_argument" "another_argument" "and_another"
Run Code Online (Sandbox Code Playgroud)
请注意,对于 strsplit,您可以使用正则表达式来确定分隔符。我会建议类似以下内容,它可以让您使用逗号或冒号来分隔您的列表:
myfilelist <- strsplit (opt$filelist,"[,:]")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6464 次 |
| 最近记录: |