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

ggpredict()能否支持4个以上变量的边际值预测?

解决ggpredict()支持4个以上变量的问题

ggpredict()的设计限制了最多同时传入4个terms参数,这是因为超过4个维度的边际效应很难通过可视化直观呈现,所以函数会自动截断多余变量。要处理5个变量的边际预测,可以用以下两种方法:

方法1:固定部分变量,分批次预测

通过condition参数固定其中一个变量的取值,对剩下的4个变量进行预测,再切换固定变量的不同水平重复操作,最后合并结果。示例代码:

# 固定BMI_cat为某一水平(比如"正常"),预测其余四个变量
pred_normal <- ggpredict(mod, 
                         terms = c("time[0:25]", "gender", "smoking", "`illness stage`"), 
                         condition = c(BMI_cat = "正常"))

# 固定BMI_cat为另一水平(比如"超重")
pred_overweight <- ggpredict(mod, 
                             terms = c("time[0:25]", "gender", "smoking", "`illness stage`"), 
                             condition = c(BMI_cat = "超重"))

# 合并所有预测结果
all_preds <- rbind(pred_normal, pred_overweight)

注:变量名illness stage包含空格,需要用反引号``包裹。

方法2:改用emmeans包计算边际效应

emmeans包支持更多变量的边际均值计算,之后可将结果转换为数据框,用ggplot自行绘制可视化:

library(emmeans)
library(ggplot2)

# 计算所有变量组合的边际均值,指定time的取值范围
emm_results <- emmeans(mod, 
                       ~ time + gender + smoking + `illness stage` + BMI_cat, 
                       at = list(time = 0:25))

# 转换为数据框
emm_df <- as.data.frame(emm_results)

# 用ggplot绘制多维度可视化,用分面展示illness stage和BMI_cat的组合
ggplot(emm_df, aes(x = time, y = emmean, color = gender, linetype = smoking)) +
  geom_line(size = 1) +
  geom_ribbon(aes(ymin = lower.CL, ymax = upper.CL, fill = gender), alpha = 0.2) +
  facet_grid(`illness stage` ~ BMI_cat) +
  labs(x = "时间", y = "预测边际值") +
  theme_minimal()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 20:22:10