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

在R中用gtsummary创建带嵌套列分组的可发表统计表格

使用gtsummary生成指定结构的均值汇总表

直接用以下代码即可实现你需要的表格:

library(gtsummary)
library(dplyr)

# 你的示例数据
Year <- c('2016','2017','2018','2016','2017','2018')
Type <- c('Fall','Concussion','Fall','Burn','Burn','Laceration')
Service <- c('Hospital','Hospital','Nursing home','Hospital','Trauma centre','Hospital')
Risk <- c(6,10,3,15,3,6)
dat <- cbind.data.frame(Year,Type,Service,Risk)

# 生成目标表格
dat %>%
  select(Type, Service, Risk, Year) %>%
  tbl_strata(
    strata = Service,
    ~ .x %>%
      tbl_summary(
        by = Year,
        missing = "no",
        include = Risk,          # 仅统计Risk变量
        group = Type,            # 将Type作为行分组
        statistic = list(Risk ~ "{mean}")  # 只展示均值
      ) %>%
      modify_header(label ~ "")  # 移除默认的"Risk"表头,让Type直接作为行标识
      # 若不需要总列,可添加:modify_column_hide(stat_0)
  )

关键参数说明:

  • group = Type:让每个Type单独占一行,展示对应分组的Risk均值
  • statistic = list(Risk ~ "{mean}"):指定单元格仅显示均值,如需保留小数位可改为"{mean:.1f}"(保留1位小数)
  • include = Risk:限定仅处理Risk变量,避免其他干扰
  • modify_header(label ~ ""):优化表头显示,让Type直接作为行的分类标识

针对你15万行的数据集,gtsummary可以高效处理,无需担心性能问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:07:31