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

gtsummary如何将两列合并为一列显示百分比和95%置信区间

library(gtsummary)
library(tidyverse)

# 生成基础比例汇总表
tbl1 <-
  trial %>%
  mutate(trt = as.factor(trt)) %>%
  select(grade, response, trt) %>%
  tbl_summary(missing = "no",  type = everything() ~ "categorical",
              statistic = all_categorical() ~ "{p}")

# 计算95%置信区间
myci2 <-
  tbl1$meta_data %>%
  filter(summary_type %in% c("categorical", "dichotomous")) %>%
  select(summary_type, var_label, df_stats) %>%
  unnest(df_stats) %>%
  mutate(
    conf.low = (p - qnorm(0.975) * sqrt(p * (1 - p) / N)) %>%
      style_percent(symbol = TRUE),
    conf.high =( p + qnorm(0.975) * sqrt(p * (1 - p) / N)) %>%
      style_percent(symbol = TRUE),
    # 此处将原逗号分隔改为横线分隔,匹配预期的区间展示格式
    ci = str_glue("{conf.low} - {conf.high}"),
    label = coalesce(variable_levels, var_label),
    row_type = ifelse(summary_type == "dichotomous", "label", "level")
  ) %>%
  select(variable, row_type, label, ci)

# 合并CI到原表、合并两列为目标格式、调整列显隐和表头
finaltbl <-
  tbl1 %>%
  modify_table_body(
    left_join,
    myci2,
    by = c("variable", "row_type", "label")
  ) %>%
  # 直接在管道中合并占比和CI为单列
  modify_table_body(
    ~.x %>% mutate(`% (95% CI)` = paste0(stat_0, " (", ci, ")"))
  ) %>%
  # 隐藏不需要的原始列
  modify_column_hide(c(stat_0, ci)) %>%
  # 设置目标列加粗表头
  modify_header(`% (95% CI)` = "**% (95% CI)**") %>%
  # 可选调整:把合并后的列移动到特征标签列后方,符合常规统计表排版逻辑
  modify_column_move(`% (95% CI)`, after = label)

# 输出最终结果
finaltbl

核心修改说明

  • 原代码生成CI字符串时使用逗号分隔,改为横线分隔即可匹配23 (21.2 - 24.5)的预期格式
  • 合并列后直接给新生成的列设置表头,无需单独给CI列配置表头
  • 所有逻辑整合到gtsummary的管道流中,代码更简洁易维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:27:02