R 语言--接收命令行参数

川长思鸟来 2022-05-28 05:23 525阅读 0赞

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

  1. args=commandArgs(T)
  2. print (args[1])
  3. print (args[2])
  4. print(args[3])
  5. print(args[4])

70

运行

Rscript test.R 1 3

70 1

Rscript test.R 1 3 4 5

70 2

测试2

  1. Args <- commandArgs()
  2. cat("Args[1]=",Args[1],"\n")
  3. cat("Args[2]=",Args[1],"\n")
  4. cat("Args[3]=",Args[3],"\n")
  5. cat("Args[4]=",Args[4],"\n")
  6. cat("Args[5]=",Args[5],"\n")
  7. cat("Args[6]=",Args[6],"\n")
  8. cat("Args[7]=",Args[7],"\n")

70 3

补充说明:

在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,这时参数无实际意义,而是以用法的形式输出。

  1. library('getopt')
  2. spec = matrix(c(
  3. 'verbose', 'v', 2, "integer",
  4. 'help' , 'h', 0, "logical",
  5. 'count' , 'c', 1, "integer",
  6. 'mean' , 'm', 1, "double",
  7. ), byrow=TRUE, ncol=4)
  8. opt = getopt(spec)
  9. print(opt$count)
  10. 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()`

}

发表评论

表情:
评论列表 (有 0 条评论,525人围观)

还没有评论,来说两句吧...

相关阅读