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

R语言gtsummary::tbl_summary生成分组中位数统计表格求助

解决方案

你需要调整tbl_summary()的统计量设置(默认对连续变量展示均值±标准差),指定为中位数(四分位数)格式,同时修正表头的错误映射,以下是调整后的代码:

# 加载必要包
library(gtsummary)
library(dplyr)

# 你的数据框
df <- structure(list(Treatment = c("Verum", "Verum", "SoC", "SoC",  "Verum"), PTN = c(7.91749000549316, 7.60503005981445, 8.45341014862061,  8.48719024658203, 7.39421987533569), HGF = c(13.0622499583508,  12.6070907710339, 12.3543298838879, 12.2434056399609, 13.6388056872632 ), FGF_21 = c(5.53692184768091, 5.28081165633569, 5.68246208510767,  5.6471217759646, 4.85877167067895), PVALB = c(8.4968900680542,  4.57206010818481, 7.59231996536255, 8.43292999267578, 6.51680994033813 )), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame" ))

# 调整后的统计表格代码
df %>%
  tbl_summary(
    by = "Treatment",
    # 指定连续变量展示中位数(四分位数)格式
    statistic = all_continuous() ~ "{median} ({p25}, {p75})",
    # 可选:给变量设置更清晰的展示标签
    label = list(
      PTN ~ "PTN",
      HGF ~ "HGF",
      FGF_21 ~ "FGF-21",
      PVALB ~ "PVALB"
    )
  ) %>%
  add_p() %>%
  sort_p() %>%
  # 修正表头:label对应左侧的蛋白指标列
  modify_header(label ~ "**蛋白指标**") %>%
  modify_spanning_header(c("stat_1", "stat_2") ~ "**Treatment Received at day = 8**") %>%
  bold_labels()

关键修改说明:

  • statistic参数:强制所有连续变量使用中位数+四分位数的统计格式,替换默认的均值±标准差,这是实现需求的核心调整。
  • modify_header修正:原代码错误地将label表头设为"Treatment",label对应表格左侧的指标名称列,改为"蛋白指标"更符合期望样式。
  • label参数:可选配置,用来给变量设置更友好的展示名称,不需要可直接删除该部分。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 11:33:12