1 、commandArgs(),是R自带的参数传递函数,属于位置参数。
args=commandArgs(T)
print (args[1])
print (args[2])
print(args[3])
print(args[4])
运行
Rscript test.R 1 3
Rscript test.R 1 3 4 5
测试2
Args <- commandArgs()
cat("Args[1]=",Args[1],"\n")
cat("Args[2]=",Args[1],"\n")
cat("Args[3]=",Args[3],"\n")
cat("Args[4]=",Args[4],"\n")
cat("Args[5]=",Args[5],"\n")
cat("Args[6]=",Args[6],"\n")
cat("Args[7]=",Args[7],"\n")
补充说明:
在unix、windows外部需要调用R脚本执行,然后又需要输入不同的参数,类似shell脚本的命令行参数输入,可以使用Rcript命令实现。
命令格式:Rscript [options] [-e expression] file [args]
file表示需要执行的脚本,[options] [-e expression] 可以有也可以不用。
[args]是参数列表。
首先需要在file文件中的第一行加入:
Args <- commandArgs()
然后按照以下格式执行
Rscript *.R 参数1 参数2 ...
在file脚本中,可以引用参数Args,
Args[1]= "/usr/local/lib64/R/bin/exec/R"
Args[2]= "--slave"
Args[3]= "--no-restore"
Args[4]="--file=a.r"
Args[5]="--args"
Args[6]==参数1
Args[7]==参数2
可见输入的参数从第六个和第七个开始。
2、getopt()函数
是getopt包的函数,需要先安装getopt包
install.packages("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)
制作脚本帮助
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()
}