R中的参数传递函数:commandArgs(),getopt().

1.commandArgs(),是R自带的参数传递函数,属于位置参数。

##test.R
args=commandArgs(T)
print (args[1])##第一个外部参数
print (args[2])##第二个外部参数
##运行脚本:Rscript test.R first second
结果:

  

2.getopt(),是getopt包的函数,需要先按照getopt包

getopt(spec = NULL, opt = commandArgs(TRUE),command = get_Rscript_filename(), usage = FALSE,debug = FALSE)

spec:一个4-5列的矩阵,里面包括了参数信息,前四列是必须的,第五列可选。

第一列:参数的longname,多个字符。

第二列:参数的shortname,一个字符。

第三列:参数是必须的,还是可选的,数字:0代表不接参数 ;1代表必须有参数;2代表参数可选。

第四列:参数的类型。logical;integer;double;complex;character;numeric

第五列:注释信息,可选。

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

library(getopt)
spec = matrix(c( 'verbose', 'v', 2, "integer", 'help' , 'h', 0, "logical", 'count' , 'c', 1, "integer", 'mean' , 'm', 1, "double", ), byrow=TRUE, ncol=4) opt = getopt(spec) print(opt$count) print(opt$mean)

  

 3.如何制作脚本的帮助:

command=matrix(c("bam","b",1,"character",
                 "bed","d",1,"character",
                 "png","p",1,"character",
                 "help","h",0,"logical"),byrow=T,ncol=4)
args=getopt(command)
if (!is.null(args$help) || is.null(args$bam) || is.null(args$png) || is.null(args$bed)) {
    cat(paste(getopt(command, usage = T), "
"))
    q()
}

  

拒绝低效率勤奋,保持高效思考
原文地址:https://www.cnblogs.com/timeisbiggestboss/p/7811009.html