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

调整gtsummary表格布局:将子类别显示在首列

实现gtsummary首列分层(物种-区域)的表格布局

需求说明

需要将物种作为主类别、所属区域作为子类别合并展示在表格首列,按季节维度(列方向)呈现统计结果,但现有代码无法实现该分层首列布局。

现有代码

加载依赖库

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

创建示例数据集

mydf <- data.frame(
  species = c("Species1", "Species1", "Species1", "Species2", "Species2", "Species2", "Species3", "Species3"),
  season = c("Spring", "Spring", "Summer", "Spring", "Spring", "Summer", "Spring", "Summer"),
  region = c("Region1", "Region2", "Region1", "Region2", "Region1", "Region1", "Region1", "Region1")
)

原有表格代码(未实现分层布局)

myTbl <- mydf %>%
  tbl_summary(
    by = season,
    missing = "no",
    type=all_continuous() ~ "continuous2",
    statistic = list(all_continuous2() ~ c("{sum}", "{median} ({min} - {max})")),
    label = list(
      species ~ "Species",
      region ~ "Region",
      season ~ "Season"
    )
  ) %>%
  modify_table_body(
    ~.x %>%
      mutate(
        across(all_stat_cols(),~gsub("^0.*", "-", .))
      )
  ) %>%
  bold_labels() %>%
  bold_levels() %>%
  modify_footnote(everything() ~ NA) %>%
  italicize_levels() %>%
  as_gt() %>%  
  tab_style(
    style = list(cell_fill(color = "#DBE5F1")),
    locations = cells_column_labels()
  )

myTbl

解决方案:使用tbl_strata实现分层首列

利用gtsummary的tbl_strata函数按物种分层,在每个物种层内展示对应区域的统计结果,从而实现首列的层级布局:

myTbl <- mydf %>%
  # 按species字段划分表格层级
  tbl_strata(
    strata = species,
    .tbl_fun = ~.x %>%
      # 层内统计各区域在不同季节的样本量
      tbl_summary(
        by = season,
        include = region,
        missing = "no",
        statistic = list(all_categorical() ~ "{n}"),
        label = list(region ~ "Region")
      ) %>%
      # 将物种名称设置为当前层的首列标题
      modify_header(label ~ "**Species: {strata}**")
  ) %>%
  # 将统计列中的0替换为"-"
  modify_table_body(
    ~.x %>%
      mutate(
        across(all_stat_cols(), ~gsub("^0$", "-", .))
      )
  ) %>%
  bold_labels() %>%
  remove_footnote() %>%
  as_gt() %>%
  # 设置列标题背景色
  tab_style(
    style = list(cell_fill(color = "#DBE5F1")),
    locations = cells_column_labels()
  )

myTbl

代码说明

  1. 分层构建:tbl_strata按species自动划分表格分组,每个物种对应一个独立的层级块
  2. 层内统计:在每个物种分组内,针对region字段统计各季节的样本数量
  3. 首列层级展示:通过modify_header将物种名称嵌入首列的分组标题,实现"物种-区域"的层级视觉效果
  4. 样式适配:保留原有需求中的0替换为"-"、列标题背景色等样式设置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:11:14