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), "\n"))
    q()
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM