You need to enable JavaScript to run this app. R中Cox回归分类变量交互项手动构造适配ggforest方法
优惠活动
大模型
产品
解决方案
定价
更多

R中Cox回归分类变量交互项手动构造适配ggforest方法

分类变量交互项适配SurvMiner::ggforest的解决方案

问题原因

  1. 三因子交互拟合结果偏差:你在拟合三因子模型时遗漏了Gender主效应项,模型设定错误导致系数估计和标准结果不一致
  2. 森林图展示异常:直接调用model.matrix输出的列(带m$前缀、交互项含特殊符号:),导致ggforest的变量标签展示错乱

三因子交互完整实现方案

步骤1:生成交互项并入原数据集

通过设计矩阵提取所有主效应和交互项,重命名为无特殊符号的列名后合并到原数据集:

library(survival)
library(survminer)
# 加载测试数据集
data <- structure(list(time = c(3, 19, 13, 45, 87, 90, 24, 75, 17, 4, 
109, 16, 14, 45, 27, 48, 9, 40, 28, 16, 8, 32, 21, 15, 12, 15, 
8, 6, 35, 43, 63, 97, 22, 34, 16, 23, 70, 9, 28, 60, 105, 24, 
32, 41, 89, 38, 24, 82, 17, 79, 62, 17, 14, 68, 66, 5, 53, 30, 
14, 66, 59, 34, 53, 17, 15, 39, 20, 14, 10, 43, 11, 12, 47, 105, 
34, 111, 84, 39, 25, 17, 44, 19, 17, 113, 31, 26, 9, 81, 9, 77, 
38, 19, 84, 22, 86, 18, 56, 113, 13, 45), status = c(1L, 1L, 
1L, 1L, 0L, 0L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 
1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 1L, 1L, 
1L, 1L, 1L, 1L, 0L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 0L, 
0L, 1L, 1L, 0L, 0L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 
1L, 1L, 1L, 0L, 1L, 1L, 0L, 0L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 0L, 1L, 1L, 1L, 0L, 1L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2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 
1L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 
2L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 
1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 
1L, 1L, 2L), .Label = c("A", "B"), class = "factor")), row.names = c(NA, 
100L), class = "data.frame")
# 生成设计矩阵,去掉截距项
inter_terms <- as.data.frame(model.matrix(~ Type * Branch * Gender, data = data)[, -1])
# 替换列名中的特殊符号,适配ggforest展示
colnames(inter_terms) <- gsub(":", "_", colnames(inter_terms))
# 合并到原数据集
data <- cbind(data, inter_terms)

步骤2:拟合Cox模型

纳入所有主效应和交互项,不使用*/:交互写法:

cox_fit <- coxph(Surv(time, status) ~ TypeB + BranchY + GenderMale + 
                   TypeB_BranchY + TypeB_GenderMale + BranchY_GenderMale + 
                   TypeB_BranchY_GenderMale, data = data)
# 验证结果和标准三因子交互模型完全一致
summary(cox_fit)

步骤3:绘制森林图

所有变量均可被ggforest正常识别,标签展示清晰:

ggforest(cox_fit, data = data)

双因子交互优化方案(解决展示异常)

针对Type×Branch双因子测试场景,优化后代码如下:

# 生成双因子交互项
inter_terms_2f <- as.data.frame(model.matrix(~ Type * Branch, data = data)[, -1])
colnames(inter_terms_2f) <- gsub(":", "_", colnames(inter_terms_2f))
data_2f <- cbind(data, inter_terms_2f)
# 拟合模型
cox_fit_2f <- coxph(Surv(time, status) ~ TypeB + BranchY + TypeB_BranchY, data = data_2f)
# 绘制正常展示的森林图
ggforest(cox_fit_2f, data = data_2f)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 15:15:05