- Published on
R 脚本接收命令行参数
- Authors

- Name
- Hongjun LI
可使用 R 语言 base 包的函数 commandArgs 在执行脚本时接收命令行参数。
commandArgs 函数
使用说明
commandArgs 返回一个包含参数信息的向量。
测试脚本 test_args.R:
args <- commandArgs()
print(args)
尝试加参数执行:
Rscript test_args.R Hello R
输出为:
[1] "/usr/lib64/R/bin/exec/R"
[2] "--slave"
[3] "--no-restore"
[4] "--file=test_args.R"
[5] "--args"
[6] "Hello"
[7] "R"
结果说明
| 位置 | 说明 | 示例 |
|---|---|---|
| 1 | R 所在的路径 | /usr/lib64/R/bin/exec/R |
| 2 | Rscript 的参数 | --slave |
| 3 | Rscript 的参数 | --no-restore |
| 4 | 运行 R 脚本的路径 | --file=test_args.R |
| 5 | 脚本参数 flag | --args |
| 6 | 第一个参数 | Hello |
| 7 | 第二个参数 | R |
参数解释
可以添加一个参数来削掉 R 脚本参数之前的参数
args <- commandArgs(trailingOnly = TRUE)
print(args)
此时脚本输出为:
[1] "Hello"
[2] "R"
commandArgs 函数只能接收位置参数,无法接收可选参数(通过 --参数名 显式接收参数)。
如需接收可选参数,可使用 argparse 包。
Writing Enriches Life.