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

如何在gt表格总汇总行中添加配对t检验统计结果?

在gt表格总汇总行添加配对t检验结果

当然可行,你可以提前计算好配对t检验的结果并整理成目标字符串格式,再通过grand_summary_rows()将其硬编码添加到总汇总行中,放在相关性结果下方。

具体实现方式

你可以选择两种硬编码方式:

  • 动态计算后生成字符串(保证结果准确性)
  • 直接写入固定字符串(适合结果固定的场景)

完整示例代码

library(tidyverse)
library(gt)
library(rstatix)

df <- structure(list(study = c("caius", "titium", "sempronius", "cicero", 
"titus"), control = c(452, 603, 243, 552, 173), treatment = c(482, 
383, 579, 360, 227), difference = c(30, -220, 336, -192, 54)), class = "data.frame", row.names = c(NA, 
-5L))

# 方式1:动态计算并格式化t检验结果字符串
t_test_result <- df %>% 
  t_test(control ~ treatment, paired = TRUE) %>% 
  mutate(result_str = str_glue("t({df}) = {round(t, 2)}, p = {round(p, 3)}", df = nrow(df)-1)) %>% 
  pull(result_str)

# 方式2:直接硬编码固定字符串(注释掉方式1,启用此行即可)
# t_test_result <- "t(4) = 0.32, p = 0.761"

df %>% gt() %>%
  grand_summary_rows(
    columns = c(control, treatment, difference),
    fns = list(Mean ~ round(mean(.)),
               SD ~ round(sd(.))), 
    missing_text = " " 
  ) %>%
  grand_summary_rows(
    columns = c(difference),
    fns = list(Correlation ~ round(cor(control, treatment), 2)), 
    missing_text = " " 
  ) %>%
  # 添加配对t检验结果的汇总行
  grand_summary_rows(
    columns = c(difference),
    fns = list(`Paired t-test` ~ t_test_result),
    missing_text = " "
  )

说明

  • 动态计算方式会根据数据自动生成准确的t检验结果字符串,适合数据可能变动的场景
  • 直接硬编码方式适合结果固定、不需要重复计算的场景,直接写入最终结果字符串即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 22:46:02