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

如何在geom_bracket()中动态应用APA格式的p值报告规则?

实现geom_bracket中p值的APA动态格式化

1. 自定义APA格式p值转换函数

先写一个严格遵循APA规则的p值格式化函数,处理三种情况:

  • p < 0.001:显示p < .001
  • 0.001 ≤ p < 0.01:保留三位小数,省略小数点前的0(如.008)
  • p ≥ 0.01:保留两位小数,省略小数点前的0(如.05)
library(dplyr)
library(stringr)

format_p_apa <- function(p) {
  case_when(
    p < 0.001 ~ "p < .001",
    p < 0.01 ~ sprintf("p = %.3f", p) %>% str_replace("0\\.", "\\."),
    TRUE ~ sprintf("p = %.2f", p) %>% str_replace("0\\.", "\\.")
  )
}

2. 生成测试数据

模拟配对样本数据(25个受试者,3种条件的重复测量):

library(tibble)
set.seed(456)
n_subjects <- 25
test_data <- tibble(
  subject_id = rep(1:n_subjects, 3),
  condition = rep(c("Control", "Treatment1", "Treatment2"), each = n_subjects),
  score = c(
    rnorm(n_subjects, 10, 1.5),          # Control组
    rnorm(n_subjects, 11.2, 1.5),        # 与Control有显著差异
    rnorm(n_subjects, 10.2, 1.5)         # 与Control差异较小
  )
)

3. 批量执行配对t检验并整理结果

循环处理需要对比的配对组,计算p值并生成APA格式标签:

library(purrr)
library(tidyr)

# 定义需对比的配对组
comparisons <- list(
  c("Control", "Treatment1"),
  c("Control", "Treatment2")
)

# 批量计算并整理结果
test_results <- map_dfr(comparisons, function(comp) {
  # 转换为宽格式用于配对t检验
  paired_data <- test_data %>%
    filter(condition %in% comp) %>%
    pivot_wider(names_from = condition, values_from = score)
  
  # 执行配对t检验
  t_test_res <- t.test(paired_data[[comp[1]]], paired_data[[comp[2]]], paired = TRUE)
  
  # 计算括号的y轴位置(取两组数据最大值+0.5)
  max_y <- test_data %>%
    filter(condition %in% comp) %>%
    pull(score) %>%
    max()
  
  tibble(
    group1 = comp[1],
    group2 = comp[2],
    p_value = t_test_res$p.value,
    y_position = max_y + 0.5
  )
}) %>%
  # 应用APA格式转换
  mutate(p_label = format_p_apa(p_value))

4. 绘图并应用格式化p值

用geom_bracket加载整理好的标签数据,直接调用p_label作为标签:

library(ggplot2)
library(ggsignif)

ggplot(test_data, aes(x = condition, y = score)) +
  geom_boxplot(fill = "lightblue", alpha = 0.7) +
  geom_jitter(width = 0.2, alpha = 0.5) +
  # 添加带APA格式p值的差异括号
  geom_bracket(
    data = test_results,
    aes(xmin = group1, xmax = group2, y.position = y_position, label = p_label),
    tip.length = 0.02,
    size = 0.8
  ) +
  labs(title = "配对组差异对比(APA格式p值)",
       x = "实验条件", y = "得分") +
  theme_minimal()

常见问题排查

如果之前自定义函数未生效,大概率是以下原因:

  • 函数未正确处理向量输入(上述函数用case_when支持向量运算)
  • 未将格式化后的p值提前存入结果数据框,而是直接在geom_bracket的label参数中调用函数(容易因环境变量问题失效)
  • 未遵循APA规则省略小数点前的0,导致格式不符合要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 19:47:41