R语言的传参

越南式三明治

1. mac或linux:

脚本第一行加:

#!/usr/bin/Rscript

2. commandArgs()传参:

测试脚本test.R:

args <- commandArgs()

print(args[1])

print(args[2])

Rscript test.R Hello R

输出为:

[1] "Hello"

[2] "R"

3. getopt传参:

install.packages("getopt")library("getopt")

# 首先将第一个参数的具体信息进行描述

# 每行五个,第五个可选,也就是说第五列可以不写

# byrow 按行填充矩阵的元素

# ncol  每行填充五个元素

spec <- matrix( c("first", "f", 2, "integer", "This is first!",

"second", "s", 1, "character", "This is second!",

"third", "t", 2, "double", "This is third!",

"help", "h", 0, "logical", "This is Help!"),

byrow=TRUE, ncol=5) 

# 使用getopt方法:

opt<-getopt(spec=spec)

# opt实际上就是一个列表,直接使用$来索引到对应的参数的值

print(opt$first)

print(opt$second)

print(opt$third)

在命令行执行

Rscript test.R -f 123 -t 1.1 -s Hello

输出为:

[1] 123

[1] "Hello"

[1] 1.1

参考:https://www.jianshu.com/p/8797972113d7

阅读微信原文

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容