0%

R语言传参之getopt

使用过程中发现使用R语言自带的CommandArgv()函数只能实现简单的传递功能,如果想要查看脚本具体的help信息似乎没办法实现。
R语言传递参数还有第二种方法,即利用getopt包的getopt()函数,它可以实现这样的功能。

1. getopt包安装

1
2
install.packages("getopt")
library(getopt)

2. getopt使用

1
2
3
#getopt()函数用法
getopt(spec = NULL, opt = NULL, command = get_Rscript_filename(),
usage = FALSE, debug = FALSE)

spec参数需要一个矩阵,这个矩阵描述接受的参数的形式以及参数对应的flag信息等等。

  • 第1列:参数的long name;
  • 第2列:参数的short name;
  • 第3列:参数是否必需,是必需的还是可选的。0代表不接受参数,1代表必须参数,2代表参数可选;
  • 第4列:参数的类型,例如:logical、integer、double、complex、character、numeric;
  • 第5列:注释信息,可选。

opt参数表示参数来源,一般使用默认,即从commandArgs()命令中接收的参数。

usage参数,默认为FALSE,这时参数无实际意义,而是以用法的形式输出。

1
2
3
4
5
6
7
8
9
10
11
12
library(getopt)

spec = matrix(c('version', 'v', 2, "logical","v1.0",
'help' , 'h', 0, "logical","help information",
'first' , 'c', 1, "integer","the first args",
'second' , 'm', 1, "double","the second args"),
byrow=TRUE, ncol=4)

opt = getopt(spec)

print(opt$first)
print(opt$second)

这样子只是完成了传递参数这一步,要想实现打印出帮助信息需要将usage参数打开,这样getopt()函数可以返回一个特定写法的帮助信息。

1
2
3
4
if (!is.null(args$help) || is.null(args$count) || is.null(args$mean)) {
cat(paste(getopt(spec, usage = T), "\n"))
q()
}

帮助信息如下:

1
2
3
4
5
Usage: test_args.R [-[-version|v]] [-[-help|h]] [-[-first|f] [<integer>]] [-[-second|s] <character>] 
-v|--version v1.0
-h|--help help information
-f|--first the first args
-s|--second the second args

也可以自己写帮助信息:

1
2
3
4
5
6
7
8
9
10
11
12
print_usage <- function(spec=NULL){
cat(' Rscript try.R --first --second
Options:
--help -h NULL
--version -v v1.0
--first -f first argument
--second -s second argument
\n')
q(status=1)
}

if(!is.null(opt$help) || is.null(opt$first) || is.null(opt$second)) {print_usage(spec)}

帮助信息如下:

1
2
3
4
5
6
Rscript try.R  --first 1 --second second
Options:
--help -h NULL
--version -v v1.0
--first -f first argument
--second -s second argument

到此为止就全部完成啦!