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

R语言dplyr处理长格式多组前后干预假设检验的问题

问题描述

我有一份长格式的多组数据集,需对每组进行干预前后的假设检验。尝试按group分组后,针对value和timepoint执行Wilcoxon配对检验,但得到的p值全部相同,不符合预期。单独筛选group='B'时,能得到唯一且合理的p值,怀疑分组方式存在问题,请求帮忙找出问题或提供更优实现方法。

原代码示例:

# Load the required library
library(dplyr)

# Set seed for reproducibility
set.seed(123)

# Create a dataframe with unique ids, timepoints, foodgroups, and values
data <- data.frame(
  id = rep(1:10, each = 2),  # Increased sample size
  timepoint = rep(c("before", "after"), times = 100),
  group = rep(c("A", "B", "C", "D", "E"), each = 40),  # Adjusted for larger sample size
  value = rnorm(200)  # Generating random values for illustration
)

# Perform t-test for each foodgroup
result <- data %>%
  group_by(group) %>%
  summarise(
    p_value = wilcox.test(value ~ timepoint, data = ., paired = TRUE)$p.value
  )

# Print the results
print(result)

单独筛选组的代码:

# Perform t-test for each foodgroup
result <- data %>%
  filter(group=='B') %>%
  summarise(
    p_value = wilcox.test(value ~ timepoint, data = ., paired = TRUE)$p.value
  )

# Print the results
print(result)

问题根源

你提供的测试数据构造存在逻辑错误,直接导致配对检验失效:

  • id生成逻辑错误:rep(1:10, each = 2)仅生成20条记录的id,但数据集总共有200条记录,后续id会循环重复,使得每个group内的id与timepoint无法形成有效配对(同一个id在同一组内对应多个before/after记录)。
  • Wilcoxon配对检验的paired=TRUE要求每个受试对象(即同一个id)在同一组内必须同时有before和after两个时间点的观测值,当前数据无法满足这个核心要求,导致检验逻辑混乱,计算出的p值错误且趋同。

解决方法

1. 修正测试数据构造逻辑

确保每个group内的每个id都有且仅有before和after两个时间点的记录:

library(dplyr)

set.seed(123)
# 构造符合配对要求的数据集:5组×10个样本×2个时间点=100条记录
data <- expand.grid(
  id = 1:10,
  timepoint = c("before", "after"),
  group = c("A", "B", "C", "D", "E")
) %>%
  mutate(value = rnorm(nrow(.)))  # 生成对应随机值

2. 正确执行分组后的Wilcoxon配对检验

此时数据已满足配对要求,直接分组计算即可:

result <- data %>%
  group_by(group) %>%
  summarise(
    p_value = wilcox.test(value ~ timepoint, paired = TRUE)$p.value,
    .groups = "drop"  # 清除分组属性,方便后续处理
  )

print(result)

3. 可选:验证配对完整性

可以先检查每个组内的id是否都包含两个时间点的记录,避免数据缺失:

# 检查是否存在id缺失时间点的情况
data %>%
  group_by(group, id) %>%
  summarise(time_count = n(), .groups = "drop") %>%
  filter(time_count != 2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 00:36:11