0%

R中从命令行传入参数CommandArgs()用法

commandArgs()是R自带的参数传递函数,本文总结其用法。

与perl的@ARGV和python的 sys.argv 类似,将来自于命令行的参数存入向量/数组中。

1
2
> args <- commandArgs()
> print(args)

命令行如下:

1
Rscript test.R arg1 arg2

输出如下:

1
2
3
4
5
6
7
[1] "C:...."	# R所在路径
[2] "--slave" # Rscript参数
[3] "--no-restore" # Rscript参数
[4] "--file=test.R" # 脚本路径
[5] "--args" # 脚本参数
[6] "arg1" #参数1
[7] "args2" #参数2

即R输入的参数并不像python、perl一样是从第一个开始的。

如下命令可以让其从1开始:

1
2
3
4
> args <- commandArgs(trailingOnly=TRUE)
> print(args)
[1] "args1"
[2] "args2"

读入文件:

1
2
> args <- commandArgs(trailingOnly=TRUE)
> file1 <- read.csv(argv[1],header = T)

命令行:

1
Rscript test.R file1.csv