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

如何用gtsummary创建按gcs行分层、location列分组的统计表?

三重分层统计表实现方案

需求说明

需要创建满足以下要求的统计表:

  • 列:展示location变量(包含缺失值)
  • 行:先按gcs变量分层,再展示age_group和sex变量的统计信息
  • 表格需包含所有变量的缺失值

示例数据与原尝试代码

示例数据框

dat <- data.frame(id = 1:20,
                  age_group = as.factor(c("66-70", "71-75", "61-65", "76-80", "61-65", "81-85", "76-80","66-70","81-85","66-70",
                                "66-70", "81-85","81-85","76-80","61-65","76-80","66-70","81-85","66-70","71-75" )),
                  location = as.factor(c("indoor", NA, "indoor", "indoor", "outdoor","indoor", "outdoor", "indoor", "indoor", "outdoor",
                               "indoor", "outdoor","indoor", NA,"outdoor", "outdoor","indoor", "outdoor","indoor", "outdoor")),
                  sex = as.factor(c("M", "F", "M", "F", NA, "M", "F", "M", "F", "M","F", "M", "F", "M", "F", "F", "M", "F", "F", "M")),
                  gcs = as.factor(c("moderate", "severe", "minor", "minor", "minor", "severe", "minor", "moderate", NA, "minor",
                          "moderate", "minor", NA, "minor", "severe", "moderate", "minor", "severe", "minor", "severe")))

原尝试代码

table <- tbl_strata(data = dat,
                    strata = location,
                    .tbl_fun = 
                      ~.x %>%
                      tbl_summary( include = ! id,
                                   by = gcs, missing = "always"))

原代码将location作为分层、gcs作为列分组,不符合需求,需调整逻辑。

修正后的实现代码

# 加载依赖包
library(gtsummary)
library(gt)

# 生成目标统计表
table <- tbl_strata(
  data = dat,
  strata = gcs,  # 按gcs实现行分层
  .tbl_fun = ~.x %>%
    tbl_summary(
      include = c(age_group, sex),  # 指定行展示的变量
      by = location,  # 列按location分组
      missing = "always",  # 强制包含缺失值
      missing_text = "Missing"  # 自定义缺失值显示文本
    ) %>%
    modify_header(label = "**变量**")  # 优化表头显示
)

# 输出表格
table

代码说明

  1. tbl_strata(strata = gcs):把数据按gcs的不同取值拆分为多个行组,实现行分层效果
  2. tbl_summary(by = location):在每个gcs分层内,以location为列展示统计结果,同时通过missing = "always"确保缺失值被纳入表格
  3. modify_header:调整表头的显示文本,提升表格可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 11:44:51