r语言读取java参数_【R语言技巧】R如何读取命令行参数

大部分人使用R语言都是交互式操作,你输入一个print('hello world!'),他就返回一个”hello world”, 高级一点叫做探索性数据分析,通过调整参数和模型的方式对数据有一定的了解,完成数据建模。

除了这种交互式模式,R语言还支持命令行传入参数,如果你听说过Rscript的话。这一篇文章就是介绍R语言如何提取命令函参数,写一个R脚本。

commandArgs()可以提取命令行参数

commandArgs(trailingOnly = FALSE)

trailingOnly:是否返回R程序自带参数

程序:commandargs.R

Args

运行:

>Rscript commandargs.R helloArgs[1] is C:\PROGRA~1\R\R-33~1.1\bin\x64\Rterm.exeArgs[2] is --slaveArgs[3] is --no-restoreArgs[4] is --file=commandargs.RArgs[5] is --argsArgs[6] is helloArgs[7] is NA

Args  #R程序自带参数,第6个才是从命令行输入的参数

Args  #此时输入的第一个参数就是程序第一个参数

程序:commandargs.R

Args

运行程序commandargs.R

>Rscript commandargs.R helloArgs[1] is helloArgs[2] is NAArgs[3] is NAArgs[4] is NAArgs[5] is NAArgs[6] is NAArgs[7] is NA

相比于commandArgs(),getopt包中getopt()函数也可以接受从终端传递参数,并且功能更加丰富;

getopt(spec = NULL, opt = commandArgs(TRUE), command = get_Rscript_filename(), usage = FALSE, debug = FALSE)参数讲解

spec:4-5列的矩阵第1列:参数完整名字;字符串

第2列:参数缩写;字符

第3列:一个整数;0:不需要传入参数;1:必须接受参数传入;2:是否有参数传入可选

第4列:参数类型:logical, integer, double, complex, character

第5列(可选):对参数添加的描述

opt:默认commandArgs(TRUE)

usage:默认usage = FALSE;如果usage = T,返回参数的使用方法程序:getopt.R

#install.packages('getopt')library('getopt')#设置spec矩阵spec = matrix(c(  'verbose', 'v', 2, 'integer',  'help' , 'h', 0, 'logical',  'count' , 'c', 2, 'integer',  'mean' , 'm', 2, 'double',  'sd' , 's', 2, 'double'), byrow=TRUE, ncol=4)opt = getopt(spec)#调用help,返回程序使用命令if ( !is.null(opt$help) ) {  cat(getopt(spec, usage=TRUE))  q(status=1)}#为参数设置默认值if ( is.null(opt$mean ) ) { opt$mean = 0 }if ( is.null(opt$sd ) ) { opt$sd = 1 }if ( is.null(opt$count ) ) { opt$count = 10 }if ( is.null(opt$verbose ) ) { opt$verbose = FALSE }print(get_Rscript_filename())print(opt$count)print(opt$mean)print(opt$sd)cat(paste(rnorm(opt$count,mean=opt$mean,sd=opt$sd),collapse='\n'));

查看程序参数:

>Rscript getopt.R -h'getopt'R3.3.3Usage: getopt.R [-[-verbose|v] []][-[-help|h]] [-[-count|c] []][-[-mean|m] []][-[-sd|s] []]

运行:

Rscript getopt.R -c 5 -m 2.2 -s 0.1Warning message:'getopt'R3.3.3[1] 'getopt.R'[1] 5[1] 2.2[1] 0.12.077751206731362.15179010973542.134172433655152.182445431265042.12912406119658参考资料

getopt:https://github.com/trevorld/getopt

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值