You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用reformulate/as.formula循环构建Cox模型时tidy_add_n()失效求助

循环构建Cox模型时tidy_add_n()失效的解决办法

问题背景

循环运行调整不同协变量子集的Cox模型,期望输出包含事件数、人年数、风险比(HR)及95%置信区间。直接调用coxph()时tidy_add_n()功能正常;但在循环中使用reformulate或as.formula构建公式时,该函数无法生成n_event和exposure列,反而生成全为缺失值的n列。

失效原因

tidy_add_n()(来自broom.helpers包)依赖模型对象中保留的原生公式结构:

  • 直接调用coxph()时,公式是原生的Surv(time, status) ~ ...形式,模型对象能正确识别生存分析的响应变量类型,因此tidy_add_n()可正常提取事件数和人年数。
  • 用字符串"Surv(time, status)"作为响应传入reformulate时,生成的公式是字符串解析后的形式,模型对象无法正确识别响应变量的生存分析结构,导致tidy_add_n()无法提取所需统计量。

解决方法

方案1:构建原生Surv对象的公式(最优解)

不要用字符串形式的Surv表达式,直接构建包含原生Surv()的公式,让模型对象保留正确的响应变量结构:

test1 <- list(time = c(4,3,1,1,2,2,3), 
              status = c(1,1,1,0,1,1,0), 
              x1 = as.factor(c(0,2,1,1,1,0,0)), 
              x2 = as.factor(c(0,0,0,0,1,1,1)))

# 定义协变量子集
covariates <- c("x1","x2")
# 构建原生Surv公式
formula <- as.formula(paste("Surv(time, status) ~", paste(covariates, collapse = " + ")))

coxph(formula, data = test1) %>%
  tidy_and_attach() %>%
  tidy_add_reference_rows() %>%
  tidy_add_estimate_to_reference_rows() %>%
  tidy_add_header_rows() %>%
  tidy_add_n()

方案2:手动计算事件数和人年数

若特殊场景下无法使用原生公式,可从原始数据中手动计算所需统计量,再合并到结果中:

test1 <- list(time = c(4,3,1,1,2,2,3), 
              status = c(1,1,1,0,1,1,0), 
              x1 = as.factor(c(0,2,1,1,1,0,0)), 
              x2 = as.factor(c(0,0,0,0,1,1,1)))

model_data <- test1
# 计算总事件数
total_n_event <- sum(model_data$status)
# 计算总人年数(若需精确统计,可使用survival包的pyears函数)
total_exposure <- sum(model_data$time)

covariates <- c("x1","x2")
reformulate(covariates, response = "Surv(time, status)") %>%
  coxph(data = model_data) %>%
  tidy_and_attach() %>%
  tidy_add_reference_rows() %>%
  tidy_add_estimate_to_reference_rows() %>%
  tidy_add_header_rows() %>%
  # 添加手动计算的统计列
  mutate(n_event = total_n_event, exposure = total_exposure)

内容的提问来源于stack exchange,提问作者trinhtran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 16:05:32