比如希望对try.R文件用如下命令行来运行
Rscript try.R -a 1 -b astring
其中参数a是整数,参数b是字符串,则
在try.R文件中可以用
library(getopt)
spec <- matrix(
c("aParameter", "a", 1, "integer",
"bParameter", "b", 1, "character"),
byrow=TRUE, ncol=4)
opt <- getopt(spec=spec)
# opt实际上就是一个列表,直接使用$来索引到对应的参数的值
print(opt$aParameter)
print(opt$bParameter)
其中spec矩阵每一列元素含义是
第一列:参数的longname,多个字符。
第二列:参数的shortname,一个字符。
第三列:参数是必须的,还是可选的,数字:0代表不接参数 ;1代表必须有参数;2代表参数可选。
第四列:参数的类型。logical;integer;double;complex;character;numeric
参考资料