在bash脚本中调用R程序时,如何解决commandArgs()无法读取第10个参数的问题?
问题:R脚本通过
commandArgs()无法读取第10个参数 我通过bash脚本运行R程序,用commandArgs()传递参数,目前传了9个参数,但程序读不到第10个。代码里尝试读取args[6]到args[10](默认前5个为系统占用参数),但args[10]始终无法获取。相关代码如下:
library(tidyverse) library(readr) library(DT) library(data.table) args <- commandArgs() table1 <- read.csv(args[6]) table2 <- read.csv(args[7]) idem <-as.character(intersect(table1$x, table2$x)) same <- data.frame( nom_colonne = idem) pasidem <-as.character(setdiff(table1$x, table2$x)) passame <- data.frame( nom_colonne = pasidem) pasidem2 <-as.character(setdiff(table2$x, table1$x)) notsame <- data.frame( nom_colonne = pasidem2) write.csv(same, args[8], row.names = F, quote=F) write.csv(passame, args[9], row.names = F, quote=F) write.csv(passame, args[10], row.names = F, quote=F)
解决方案(无需重写核心逻辑)
方法1:使用trailingOnly = TRUE获取用户参数
commandArgs()默认返回所有启动参数(包括R自身的系统参数,比如--slave、--no-restore),手动传参的位置会随系统参数数量变化,导致索引偏移。改用trailingOnly = TRUE可直接获取用户手动传递的所有参数,无需计算系统参数占用的位置:
修改代码中获取参数的行:
args <- commandArgs(trailingOnly = TRUE)
之后参数索引对应关系变为:
- 第一个手动传参:
args[1](对应原代码的args[6]) - 第二个手动传参:
args[2](对应原代码的args[7]) - ...
- 第五个手动传参:
args[5](对应原代码的args[10])
修改后的完整参数读取和写入部分:
table1 <- read.csv(args[1]) table2 <- read.csv(args[2]) # ... 中间逻辑保持不变 ... write.csv(same, args[3], row.names = F, quote=F) write.csv(passame, args[4], row.names = F, quote=F) write.csv(passame, args[5], row.names = F, quote=F)
这个方法从根源解决了参数位置偏移问题,适配所有R启动场景。
方法2:临时应急(不修改核心逻辑)
如果暂时不想调整参数索引,可先打印所有参数确认实际位置:
在代码开头添加:
print(args)
运行后查看输出,找到第10个用户参数对应的实际索引,将代码中的args[10]替换为该索引即可。但此方法依赖当前R启动的系统参数数量,换环境后可能失效,仅作为临时方案。
内容的提问来源于stack exchange,提问作者guillaume
相关产品推荐
相关产品推荐

