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

如何用as_forest_plot输出分组tbl_uvregression森林图及报错解决

解决as_forest_plot输入类错误的方案

问题根源

报错Error: x= must be class 'tbl_regression' or 'tbl_uvregression'说明你传入的df_uv不是gtsummary包生成的回归表格对象,大概率是被转换成了普通数据框(data.frame/tibble),而as_forest_plot仅支持tbl_uvregression或tbl_regression类型的输入。

修复步骤

1. 验证输入对象类型

先运行以下代码确认df_uv的类:

class(df_uv)

如果输出不含tbl_uvregression,说明对象类型错误,需要重新构建正确的输入对象。

2. 正确构建分组回归表格并生成森林图

若要生成多组数据的单变量回归森林图,需按以下流程操作:

  • 为每组数据分别生成tbl_uvregression对象
  • 用tbl_stack()合并为堆叠式回归表格
  • 将合并后的对象传入as_forest_plot

示例代码如下:

# 加载依赖包
library(gtsummary)
library(bstfun)
library(forestplot)

# 拆分数据为两组(以trial数据集为例)
data(trial)
group_drug <- trial %>% filter(trt == "Drug")
group_placebo <- trial %>% filter(trt == "Placebo")

# 分别生成单变量逻辑回归表格
uv_drug <- tbl_uvregression(
  data = group_drug,
  method = glm,
  y = response,
  method.args = list(family = binomial),
  exponentiate = TRUE  # 输出OR值
)

uv_placebo <- tbl_uvregression(
  data = group_placebo,
  method = glm,
  y = response,
  method.args = list(family = binomial),
  exponentiate = TRUE
)

# 堆叠两个表格并添加分组标题
stacked_uv <- tbl_stack(
  list(uv_drug, uv_placebo),
  group_header = c("药物组", "安慰剂组")
)

# 生成森林图
forrest <- as_forest_plot(
  stacked_uv,
  col_names = c("OR", "p值"),
  graph.pos = 2,
  boxsize = 0.3,
  title_line_color = "darkblue",
  col = forestplot::fpColors(box = "darkred", lines = "black", zero = "gray50"),
  shapes_gp = forestplot::fpShapesGp(default = gpar(lineend = "square", linejoin = "mitre", lwd = 2, col = "black")),
  box = gpar(fill = "darkred", col = "black"),
  txt_gp = fpTxtGp(ticks = gpar(cex = 0.9), xlab = gpar(cex = 1.2, vjust = 3.5)),
  zero = 1, cex = 0.9, lineheight = "auto", colgap = unit(6, "mm"),
  lwd.ci = 1, ci.vertices = TRUE, ci.vertices.height = 0.4
)

# 输出森林图
print(forrest)

3. 常见错误排查

  • 禁止将tbl_uvregression结果用as.data.frame()转换为普通数据框,这会丢失tbl_uvregression类属性
  • 若使用group_by()处理数据,确保最终生成的对象仍是tbl_uvregression类型,而非分组数据框
  • 版本不兼容可能导致类识别失败,建议更新依赖包到最新版本:
update.packages(c("gtsummary", "bstfun"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:20:32