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

如何在gtsummary分层tbl_summary表格的各列添加样本量n?

解决方案

要在每个分组列中添加样本量n计数,只需修改add_n()函数的参数,指定location = "column_spanner"即可将样本量显示在分组列的标题区域,与你提供的示例图效果一致。

修改后的完整代码:

mtcars %>%
    select(am, cyl, mpg, hp) %>%
    dplyr::mutate(
        cyl = paste(cyl, "Cylinder"),
        am = factor(am, labels = c("Automatic", "Manual"))
    ) %>%
    tbl_strata(
        strata = cyl,
        ~.x %>%
            tbl_summary(
                by = am,
                type = where(is.numeric) ~ "continuous"
            ) %>% 
            add_n(location = "column_spanner") %>%  # 关键修改:指定样本量显示位置
            modify_header(all_stat_cols() ~ "**{level}**")
    )

说明

  • add_n(location = "column_spanner")会将每个分组的样本量n嵌入到对应列的标题栏中,替代默认在表格顶部单独显示一行样本量的样式。
  • 保留modify_header()的设置,确保分组列标题以加粗样式显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 07:50:15