对于经常与 Linux 打交道的生物信息分析童鞋们,我们今天分享一下怎么在命令行下通过传递参数(类似perl、python) 的方式执行 R 脚本。
一般来说,命令行下使用 Rscript 执行 R 脚本,需要下面几方面信息:
一个输入的文件名(文件通常为 text 文本,包含了用于 R 处理的输入数据信息)
一个可选的附加参数(如,输出的文件名:使用者不提供的话,通过程序指定默认值)
R 的方式接收参数
这种方式最常用的方法就是使用 commandArgs 函数。例如我们创建一个 testScript-1.R 的 R 程序:
#!/usr/bin/env Rscript
args = commandArgs(trailingOnly=TRUE)
## test if there is at least one argument: if not, return an error
if (length(args)==0) {
stop("At least one argument must be supplied (input file).n", call.=FALSE)
} else if (length(args)==1) {
# default output file
args[2] = "out.txt"
}
## program ...
df = read.table(args[1], header=TRUE)
df_out = t(df)
write.table(df_out, file=args[2], row.names=TRUE, col.name=FALSE)
这样,我们就可以在命令行下执行 testScript-1.R:
$ Rscript --vanilla testScript-1.R iris.txt out.txt
或者:
$ Rscript --vanilla testScript-1.R iris.txt
args = commandArgs(trailingOnly=TRUE),运行会产生一个字符串向量 args,该向量包含了 iris.txt 和 out.txt 两项信息。
test 部分为缺失以及需要指定的默认值处理。
program 部分为 testScript-1.R 接收参数后的程序处理:把输入文件行列转置,最后把转置后的结果保存到 out.txt。
然而,当我们不输入任何文件参数时:
$ Rscript --vanilla testScript-1.R
Error: At least one argument must be supplied (input file).
Execution halted
Python 的方式接收参数
这是我们今天要讲的重点:利用 R optparse 包在命令行传递参数。optparse 主要包含了 下面几个功能:
make_option,用于选项声明,包括 flags, types, default values 以及 help messages。
OptionParser,用于读取传递给 R 脚本的参数。
parse_args,用于根据 make_option 的声明对 OptionParser 传递的参数进行解析。
下面,我们以创建一个名字为 testScript-2.R 传递参数程序为例,对 optparse 的使用进行详细说明。
#!/usr/bin/env Rscript
library("optparse")
option_list = list(
make_option(c("-f", "--file"), type="character", default=NULL, help="dataset file name", metavar="character"),
make_option(c("-o", "--out"), type="character", default="out.txt", help="output file name [default = %default]", metavar="character")
);
opt_parser = OptionParser(option_list=option_list);
opt = parse_args(opt_parser);
这个程序会产生一个 opt 的列表,它包含了 option_list 自定义排序的所有参数,我们通过 opt$file、opt$out 就能使用具体的参数。
if (is.null(opt$file)){
print_help(opt_parser)
stop("At least one argument must be supplied (input file).", call.=FALSE)
}
print_help 会打印该选项在 option_list 中的帮助信息。
## program ...
df = read.table(opt$file, header=TRUE)
df_out = t(df)
write.table(df_out, file=opt$out, row.names=TRUE, col.name=FALSE)
print_help 会打印该选项在 option_list 中的帮助信息。
在命令行下,我们执行:
或者:
最后,完整命令行下执行 testScript-2.R 如下:
$ Rscript --vanilla testScript-2.R -f iris.txt
# 或者:
$ Rscript --vanilla testScript-2.R -f iris.txt -o out.txt
ok,今天就介绍到这里。optparse 更多详细的信息,请参考:
https://cran.r-project.org/web/packages/optparse/index.html
https://cran.r-project.org/web/packages/optparse/optparse.pdf
https://cran.r-project.org/web/packages/optparse/vignettes/optparse.html
本文分享自微信公众号 - 生信科技爱好者(bioitee)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。
最后
以上就是完美皮卡丘最近收集整理的关于R 包 optparse 之命令行参数传递的全部内容,更多相关R内容请搜索靠谱客的其他文章。
发表评论 取消回复