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

如何在gtsummary/bstfun的as_forest_plot函数中实现分类变量层级缩进?

问题:gtsummary森林图分类变量层级缩进失效,无法显示参考水平

使用gtsummary包的实验性函数as_forest_plot生成模型系数森林图时,遇到两个问题:

  • 分类变量的层级缩进无法实现,尝试modify_column_indent函数未成功
  • 无法显示分类变量的参考水平

原代码如下:

library(titanic)
library(tidyverse, warn.conflicts = FALSE)
library(gtsummary, warn.conflicts = FALSE)
library(bstfun, warn.conflicts = FALSE)
library(magrittr, warn.conflicts = FALSE)
library(janitor, warn.conflicts = FALSE)


titanic::titanic_train %>% 
  clean_names %>% 
  select(-c(name, parch, ticket, cabin, embarked)) %>% 
  mutate(pclass = factor(pclass)) %>% 
  glm(survived ~ . - passenger_id, data = ., family = "binomial") %>%
  tbl_regression(exponentiate = TRUE) %>% 
  modify_column_indent(columns = label, rows = (header_row == TRUE)) %>%
  modify_cols_merge(
  pattern = "{estimate} ({ci})",
  rows = !is.na(estimate)
) %>%
  modify_header(estimate = "OR (95% CI)") %>%
  as_forest_plot( 
    col_names = c("estimate", "p.value"),
    col = forestplot::fpColors(box = "darkred"))

输出结果:
输出结果


解决方案

1. 核心问题分析

  • modify_column_indent的行选择条件错误:原代码中rows = (header_row == TRUE)仅针对表头行,而非分类变量的子行
  • 默认未显示参考水平:tbl_regression默认隐藏分类变量的参考水平,需手动开启
  • as_forest_plot作为实验性函数,需要确保缩进设置能正确传递到forestplot的标签中

2. 修改后的代码

library(titanic)
library(tidyverse, warn.conflicts = FALSE)
library(gtsummary, warn.conflicts = FALSE)
library(bstfun, warn.conflicts = FALSE)
library(magrittr, warn.conflicts = FALSE)
library(janitor, warn.conflicts = FALSE)

titanic::titanic_train %>% 
  clean_names %>% 
  select(-c(name, parch, ticket, cabin, embarked)) %>% 
  mutate(pclass = factor(pclass)) %>% 
  glm(survived ~ . - passenger_id, data = ., family = "binomial") %>%
  # 开启参考水平显示
  tbl_regression(exponentiate = TRUE, show_reference_rows = TRUE) %>% 
  # 为分类变量的子行添加缩进(label与variable不同的行即为子行)
  modify_column_indent(columns = label, rows = variable != label) %>%
  modify_cols_merge(
    pattern = "{estimate} ({ci})",
    rows = !is.na(estimate)
  ) %>%
  # 补全参考水平的统计值,避免森林图空值
  modify_table_body(
    mutate,
    estimate = ifelse(is.na(estimate), 1, estimate),
    ci = ifelse(is.na(ci), "1.00 (1.00, 1.00)", ci)
  ) %>%
  modify_header(estimate = "OR (95% CI)") %>%
  as_forest_plot( 
    col_names = c("estimate", "p.value"),
    col = forestplot::fpColors(box = "darkred")
  )

3. 关键修改说明

  • 显示参考水平:给tbl_regression添加show_reference_rows = TRUE参数,让分类变量的参考水平行显示出来
  • 正确设置缩进:将modify_column_indent的行条件改为rows = variable != label,针对分类变量的子行(非主变量行)添加缩进
  • 补全参考水平统计值:通过modify_table_body将参考水平的estimate设为1,CI设为(1.00,1.00),保证森林图显示完整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:24:17