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

如何在tbl_summary中与均值(标准差)同行正确展示置信区间

解决gtsummary中置信区间与均值同行显示的问题

要将置信区间(CI)与Mean (SD)显示在同一行,你可以在生成表格后,通过modify_table_body函数合并对应行的内容,具体代码如下:

library(gtsummary)

iris %>% 
  select(Sepal.Length, Sepal.Width, Species) %>% 
  tbl_summary(by = Species,
              type = all_continuous() ~ "continuous2",
              statistic = all_continuous() ~ c(
                "{mean} ({sd})",
                "{median} ({p25}, {p75})",
                "{min}, {max}"
              ),
              missing = "no", digits = everything() ~ 1) %>% 
  add_ci(include = all_continuous(),
         statistic = all_continuous()~ "{conf.low}, {conf.high}") %>%
  # 合并CI到Mean(SD)行并移除CI单独行
  modify_table_body(
    ~ .x %>%
      dplyr::group_by(variable) %>%
      dplyr::mutate(
        stat_display = case_when(
          label == "Mean (SD)" ~ paste0(stat_display, " [", dplyr::filter(., label == "95% CI")$stat_display, "]"),
          TRUE ~ stat_display
        )
      ) %>%
      dplyr::filter(label != "95% CI") %>%
      dplyr::ungroup()
  )

代码说明:

  1. 先按原逻辑生成包含均值、中位数、极值的表格,并添加置信区间行;
  2. 使用modify_table_body对表格数据进行分组处理:
    • 按变量分组,找到每个变量对应的Mean (SD)行和95% CI行;
    • 将CI的内容以[置信区间]的格式拼接到均值行的统计值后;
    • 过滤掉单独的CI行,最终实现两者同行显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 12:33:16