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

如何用gtsummary扩展小数位数,实现p值<0.0001的显示?

解决gtsummary tbl_summary小p值显示<0.0001的问题

方法1:直接修改p值格式化规则

这是最简便的方案,通过modify_fmt_fun调用fmt_pvalue函数,调整阈值和小数位数即可满足期刊要求:

library(gtsummary)

# 示例:分组描述统计+Wilcoxon检验,修改p值显示格式
trial %>%
  select(trt, age, marker) %>%
  tbl_summary(by = trt) %>%
  add_p(test = everything() ~ "wilcox.test") %>%
  modify_fmt_fun(
    stat = "p.value",
    fmt_fun = function(x) fmt_pvalue(x, digits = 4, threshold = 0.0001)
  )
  • digits=4:保证p值最多显示4位小数
  • threshold=0.0001:设定p值小于该值时,显示为<0.0001

方法2:自定义统计列(按需扩展)

如果需要同时展示检验统计量(如Wilcoxon的W值)和格式化后的p值,可以自定义统计函数并通过add_stat添加:

# 自定义Wilcoxon检验函数,返回格式化后的统计量和p值
my_wilcox_stat <- function(data, variable, by, ...) {
  test_res <- wilcox.test(data[[variable]] ~ data[[by]], ...)
  list(
    stat = glue::glue("W = {round(test_res$statistic, 1)}"),
    p_val = fmt_pvalue(test_res$p.value, digits = 4, threshold = 0.0001)
  )
}

# 应用到表格
trial %>%
  select(trt, age, marker) %>%
  tbl_summary(by = trt) %>%
  add_stat(
    fns = everything() ~ my_wilcox_stat,
    location = "level"
  ) %>%
  modify_header(stat_1 ~ "**Wilcoxon Test (W / p-value)**")

这种方式可灵活控制统计列的内容和格式,适合需要展示更多检验细节的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 18:03:18