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

如何在分组gt_summary表格中使用gtreg包的tbl_listing

问题解决:分组gt_summary表格堆叠异常的修正

核心问题分析

原代码存在两个关键问题导致堆叠失败:

  • tbl_listing调用时传入未定义的df_en对象,且生成的表格结构与tbl_summary输出的表格(包含group1/group2两列)不匹配,tbl_stack要求堆叠的表格必须有一致的列结构
  • 第一个表格的预处理逻辑错误,未生成与第二个表格对应的分组统计列

修正后的代码

library(gtsummary)
library(dplyr)
library(tidyr)
library(gtreg)

# 处理第一个数据集,生成适合tbl_summary的结构
df <- structure(list(id = c("patient1", "patient2", "patient3", "patient4", 
"patient5"), x = c("h,a,a", "i", "i", "i,a,e", "h")), class = "data.frame", row.names = c(NA, 
-5L))

# 重新预处理:拆分x后,保留每个记录的group信息
df_processed <- 
  df %>%
  mutate(group = c(rep("group1", 3), rep("group2", 2))) %>%
  separate_rows(x, sep = ",") %>%
  select(id, group, x)

# 用tbl_summary生成和第二个表格结构一致的分组统计表格
tbl <- df_processed %>%
  tbl_summary(
    by = group,
    type = all_categorical() ~ "categorical",
    statistic = all_categorical() ~ "{n}/{N} ({p}%)",
    label = x ~ "变量X" # 可选:添加变量标签
  )

# 处理第二个数据集生成表格
df1 <- structure(list(id = c("patient1", "patient2", "patient3", "patient4", 
"patient5"), y = c("yes", "no", "yes", "yes", "no")), class = "data.frame", row.names = c(NA, 
-5L))

tbl1 <- df1 %>%
  mutate(group = c(rep("group1", 1), rep("group2", 4))) %>% 
  select(-id) %>% 
  tbl_summary(
    by = group,
    type = all_categorical() ~ "categorical",
    statistic = list(all_continuous() ~ "{median} ({min}-{max})",
                     all_categorical() ~ "{n}/{N} ({p}%)"),
    label = y ~ "变量Y" # 可选:添加变量标签
  )

# 堆叠表格,此时结构完全匹配,可正常堆叠
tbl_combined <- tbl_stack(tbls = list(tbl, tbl1))
tbl_combined

关键修正点

  • 放弃手动计算百分比,改用tbl_summary自动处理,确保统计格式与第二个表格统一
  • 调整第一个数据集的预处理逻辑,保留group字段,让tbl_summary生成与第二个表格相同列数(group1/group2)的统计表格
  • 移除错误的tbl_listing调用,改用tbl_summary生成结构一致的表格,保证tbl_stack的兼容性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 06:10:58