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

如何在tbl_summary中为连续变量正确使用add_overall与add_ci?

解决tbl_summary中同时添加Overall列与置信区间(CI)的问题

问题描述

需要制作包含add_overall和add_ci的统计表格,最初代码顺序导致Overall列无置信区间;调整顺序后运行报错,且仅分类变量场景下代码正常,连续变量(使用continuous2类型)出现如下错误:

Error in `map()`:
ℹ In index: 1.
Caused by error in `dplyr::relocate()`:
ℹ In argument: `all_of(stat_cols_in_order)`.
Caused by error in `all_of()`:
! Can't subset elements that don't exist.
✖ Element `ci_stat_0` doesn't exist.
Run `rlang::last_trace()` to see where the error occurred.

问题原因

使用continuous2类型时,add_overall()新增的整体列统计量列名为stat_0,但add_ci()默认会尝试寻找未生成的ci_stat_0列,导致索引错误;同时默认仅针对分组列处理CI的逻辑,无法覆盖新增的Overall列。

解决代码

通过明确add_overall的统计量格式,并指定add_ci的目标列与对应统计行的CI格式,即可实现需求:

iris %>% 
  tbl_summary(
    by = Species,
    type = all_continuous() ~ "continuous2",
    statistic = all_continuous() ~ c(
      "{mean}+-{sd}",
      "{median} ({p25} - {p75})",
      "{min} - {max}"
    )
  ) %>%
  # 添加Overall列时同步指定统计量,保证列结构一致
  add_overall(
    last = TRUE,
    statistic = all_continuous() ~ c(
      "{mean}+-{sd}",
      "{median} ({p25} - {p75})",
      "{min} - {max}"
    )
  ) %>%
  # 指定为所有统计列添加CI,并仅针对均值行设置CI格式
  add_ci(
    target = all_stat_cols(),
    statistic = all_continuous() ~ "{mean} ({ci})",
    # 仅对均值所在的统计行应用CI(中位数、极值无CI意义)
    rows = all_continuous() & row_type == "statistic" & str_detect(label, "Mean")
  )

补充说明

  • target = all_stat_cols():让add_ci处理包括Overall列在内的所有统计列
  • rows参数:限定仅对均值统计行添加CI,避免对无CI意义的统计量(中位数、极值)做无效处理
  • 若需要保留原mean±sd格式并追加CI,可调整statistic参数为"{mean}+-{sd} ({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.24 18:52:49