如何将变量名后缀传入自定义的cox比例风险回归函数?
批量运行带动态变量名的survey::svycoxph回归解决方案
问题背景
原单变量回归代码可正常运行:
# Run cox proportional hazards regressions survey::svycoxph(Surv( time = fu_time_PJP, event = fu_status_PJP) ~ prophied, design = survey::svydesign( ids = ~1, weights = ~wts, data = df_ptm), weights = wts, id = patient_id, data = df_ptm)
需要批量运行十几组回归,通过传入后缀(如"PJP")自动指定Surv中的time(fu_time_+后缀)和event(fu_status_+后缀)变量,但尝试{{}}、[[]]、enquo()、parse(paste)等方法均报错Error... all variables must be in design.,无效函数代码如下:
# Run cox proportional hazards regressions cox_fun <- function(x) { survey::svycoxph(Surv( time = paste0("fu_time_", x), event = paste0("fu_status_", x) ~ prophied, design = survey::svydesign( ids = ~1, weights = ~wts, data = df_ptm), weights = wts, id = patient_id, data = df_ptm) } cox_fun("PJP")
有效解决方案
方案1:构造完整公式字符串
核心思路是将动态变量名拼接成完整的模型公式字符串,再转换为公式对象,让survey::svycoxph正确识别数据中的变量:
# 批量cox回归函数 cox_fun <- function(x) { # 拼接动态变量名 time_var <- paste0("fu_time_", x) event_var <- paste0("fu_status_", x) # 构造完整模型公式 model_formula <- as.formula(paste0("Surv(", time_var, ", ", event_var, ") ~ prophied")) # 创建调查设计(建议提前在函数外定义,避免重复计算) design <- survey::svydesign( ids = ~1, weights = ~wts, data = df_ptm ) # 执行cox回归 survey::svycoxph(model_formula, design = design, id = patient_id, data = df_ptm) } # 调用示例 cox_fun("PJP")
方案2:使用rlang的符号注入
利用rlang包的符号转换与注入功能,直接将字符串变量名转换为数据中的变量引用:
library(rlang) cox_fun <- function(x) { # 将字符串转换为变量符号 time_var <- sym(paste0("fu_time_", x)) event_var <- sym(paste0("fu_status_", x)) # 创建调查设计 design <- survey::svydesign( ids = ~1, weights = ~wts, data = df_ptm ) # 注入符号到Surv表达式中 survey::svycoxph(Surv(time = !!time_var, event = !!event_var) ~ prophied, design = design, id = patient_id, data = df_ptm) } # 调用示例 cox_fun("PJP")
报错原因说明
原函数直接将字符串传给Surv的time和event参数,这会被当作普通字符值而非数据中的变量引用。survey包的函数要求所有变量必须存在于design指定的数据集内,因此必须通过公式对象或符号注入的方式,让函数正确识别变量名对应的数据集列。
内容的提问来源于stack exchange,提问作者Michael Putman
相关产品推荐
相关产品推荐

