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

如何将gtsummary中t.test列设为2位小数及调整CI列格式

解决tbl_summary中t.test列小数位数与CI列格式问题

一、设置t.test相关列(统计量/ p值)为2位小数

你之前在tbl_summary()中传入style_fun报错,是因为该函数根本没有这个参数。调整列的格式需要用modify_fmt_fun(),分别针对统计量列和p值列设置小数位数:

  • 统计量列(t值):通过modify_fmt_fun(statistic ~ style_number(digits = 2))指定2位小数
  • p值列:添加modify_fmt_fun(p.value ~ style_number(digits = 2))来统一格式(如果需要保留科学计数法,可改用style_pvalue(digits = 2))

二、修改CI列格式为conf.low - conf.high

默认CI列用逗号分隔上下限,只需自定义一个字符串替换函数,传入modify_fmt_fun()处理ci列即可:

fmt_ci <- function(x) {
  stringr::str_replace(x, ", ", " - ")
}

完整修改后的代码

library(gtsummary)
library(dplyr)
library(stringr)

car <- mtcars[,c("am", "mpg", "qsec", "disp")]

# 自定义CI格式化函数
fmt_ci <- function(x) {
  stringr::str_replace(x, ", ", " - ")
}

car %>%
  dplyr::select(am, mpg, qsec, disp) %>%
  tbl_summary(
    by = "am",
    statistic = list(all_continuous() ~ "{mean} (±{sd})"),
    digits = all_continuous() ~ 2
  ) %>%
  add_p(test = all_continuous() ~ "t.test") %>%
  add_ci(digits = all_continuous() ~ 2) %>% # 先生成CI列,指定小数位数
  modify_header(statistic ~ "**Test Statistic**") %>%
  # 设置统计量和p值的小数位数
  modify_fmt_fun(statistic ~ style_number(digits = 2)) %>%
  modify_fmt_fun(p.value ~ style_number(digits = 2)) %>%
  # 修改CI列分隔符为连字符
  modify_fmt_fun(ci ~ fmt_ci)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:50:28