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

如何使用tbl_summary添加唯一患者总例数统计信息

gtsummary 补充唯一患者总例数实现方案

核心说明

你的原始代码存在语法问题:tbl_summary() 函数未正确闭合,后续的label、statistic等参数没有传入函数内部,需要先修正语法再添加唯一患者数的统计逻辑。
tbl_summary() 默认按数据行计数(即你的场景下的9条手术适应症观测),要补充唯一患者总例数,只需要先计算去重后的患者总数,再通过modify_header()把两个计数同时展示在表头即可,不需要改动原始统计逻辑。

完整可运行代码

library(data.table)
library(tidyverse)
library(gtsummary)

# 读入示例数据
participant.index = c(1,2,3,3,4,5,5,6,7)
repeat.instance = c(1,1,1,1,1,1,1,1,1)
indication.surgery = c("ibs","infection", "infection", "renalstones", "ibs", "infection",
                       "infection", "ibs","tumour")
date.surgery =c("2019-01-10", "2019-01-01", "2018-01-01", "2018-01-01", "2017-09-10",
                "2000-09-09","2015-01-10","2015-01-10","2006-09-09")
mydata = data.table(participant.index,repeat.instance,indication.surgery,date.surgery)

# 提前计算唯一患者总例数
n_unique_patient <- uniqueN(mydata$participant.index) # 计算结果为7

mydata %>%
  select(indication.surgery) %>%
  tbl_summary(
    label = list(indication.surgery ~ "Indication for Surgery"),
    statistic = list(all_categorical() ~ "{n}  ({p}%)"),
    missing_text = "(Missing Observations)",
    percent = c("cell")
  ) %>%
  # 修改表头,同时展示总观测数和唯一患者数
  modify_header(
    stat_0 ~ "**总手术指征记录 N = {N}**  
    *唯一手术患者 n = {n_unique_patient}*"
  ) %>%
  modify_table_styling(spanning_header =  "Indications for Surgery") %>%
  modify_caption("**Table 1. Indication for Surgery**") %>%
  # 修改脚注明确统计口径
  modify_footnote(
    all_stat_cols() ~ "单元格数值为对应指征的观测数,占比为占总9条观测的比例;表头同时标注去重后的总患者例数"
  )

可选扩展

如果你需要同时统计每个手术适应症对应的唯一患者数,可以自定义统计函数传入statistic参数,示例逻辑如下:

# 自定义统计函数:同时输出观测数、占比、对应唯一患者数
custom_stat <- function(data, variable, ...) {
  res <- data %>%
    group_by(.data[[variable]]) %>%
    summarise(
      n_obs = n(),
      n_pat = uniqueN(participant.index),
      .groups = "drop"
    )
  # 拼接展示文本
  res$label <- paste0(res$n_obs, " (", res$n_pat, "例患者, ", round(res$n_obs/nrow(data)*100,1), "%)")
  setNames(res$label, res[[variable]])
}

把这个函数传入tbl_summary的statistic参数即可同时展示每个指征对应的患者数。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 01:49:15