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

如何在gtsummary的tbl_continuous表格中添加行总计?

解决tbl_continuous表格添加行总计/总计列的问题

首先修正你代码中的拼写错误(ibrary → library),然后根据你的需求提供两种解决方案:

方案1:为每个分组行添加总样本数

如果你需要在每个smoke分组的行中显示该组的总样本数(行级总计),可以调整add_n()的参数,指定location = "level":

library(tidyverse)
library(gtsummary)
set.seed(42)
n <- 1000
dat <- data.frame(q=runif(n, min=45, max=85),
                  r=runif(n, min=2.4, max=6.0),
                  s=runif(n, min=24, max=60),
                  t=runif(n, min=0.28, max=1.73),
                  time=1)

patient <- data.frame(id=1:n,
                      treat = factor(sample(c('Treat','Control'), n, rep=TRUE, prob=c(.5, .5))),
                      age=sample(18:80, n, replace=TRUE),
                      sex = factor(sample(c('Male','Female'), n, rep=TRUE, prob=c(.6, .4))),
                      smoke=factor(sample(c("Never", 'Former', 'Current'), n, rep=TRUE, prob=c(.25, .6, .15))),
                      bmi=runif(n, min=16, max=45))
df <- cbind(patient, dat)

df %>% 
  select(q, treat, smoke) %>% 
  tbl_continuous(variable = q, 
                 by = treat,
                 include = smoke) %>%
  # 在每个smoke分组行添加该组总样本数
  add_n(location = "level",
        statistic = "{n}",
        label = "总样本数")

方案2:添加总计列(整体统计量)

如果你的需求是增加一列展示不区分treat分组的q整体统计量(列级总计),使用add_overall()函数更合适:

df %>% 
  select(q, treat, smoke) %>% 
  tbl_continuous(variable = q, 
                 by = treat,
                 include = smoke) %>%
  # 添加总计列,展示所有样本的统计量
  add_overall(label = "总计") %>%
  # 在表头添加各组样本数(可选)
  add_n(location = "header")

关键说明

  • 默认的add_n()会在表格顶部添加分组的样本数,而location = "level"参数可以将样本数嵌入到每个分组行中。
  • add_overall()是gtsummary专门为分组表格添加总计列的函数,适用于tbl_continuous、tbl_summary等多种表格类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 05:25:53