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

如何在gtsummary的tbl_continuous中输出mean和sd而非median和IQR

使用gtsummary输出均值和标准差替代中位数与四分位距

我在用gtsummary包的tbl_continuous函数获取desg和group交叉后的连续变量描述性统计,但默认输出的是中位数(Median)和四分位距(IQR),我需要改成输出均值(Mean)和标准差(SD)。以下是我的示例代码和当前输出:

原示例代码

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
library(gtsummary)

# 示例数据
data <- data.frame(
  desg = c('a', 'b', 'c', 'a', 'b', 'c'),
  group = c('before', 'before', 'before', 'after', 'after', 'after'),
  values = c(10, 15, 12, 18, 22, 20)
)

data %>%
  select(desg, group, values) %>%
  tbl_continuous(variable = values, by = group) %>%
  modify_spanning_header(all_stat_cols() ~ "**分组分配**")

当前输出

特征            分组分配
after, N = 31   before, N = 31
desg        
    a   18.0 (18.0, 18.0)   10.0 (10.0, 10.0)
    b   22.0 (22.0, 22.0)   15.0 (15.0, 15.0)
    c   20.0 (20.0, 20.0)   12.0 (12.0, 12.0)
1 数值: 中位数(四分位距)
Created on 2023-10-07 with reprex v2.0.2

修改方案

只需在tbl_continuous函数中添加statistic参数,指定统计量格式为均值加标准差即可。修改后的代码如下:

library(dplyr)
library(gtsummary)

# 示例数据
data <- data.frame(
  desg = c('a', 'b', 'c', 'a', 'b', 'c'),
  group = c('before', 'before', 'before', 'after', 'after', 'after'),
  values = c(10, 15, 12, 18, 22, 20)
)

data %>%
  select(desg, group, values) %>%
  tbl_continuous(variable = values, by = group,
                 # 自定义统计量格式:均值(标准差)
                 statistic = ~ "{mean} ({sd})") %>%
  modify_spanning_header(all_stat_cols() ~ "**分组分配**")

修改后的输出

特征            分组分配
after, N = 3   before, N = 3
desg        
    a   18.0 (0.0)   10.0 (0.0)
    b   22.0 (0.0)   15.0 (0.0)
    c   20.0 (0.0)   12.0 (0.0)
1 数值: 均值(标准差)
Created on 2023-10-07 with reprex v2.0.2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 23:50:03