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

循环执行样本t-test后差异值与P值恒常的问题排查

问题诊断与修正方案

核心问题:t检验参数调用错误

你当前的t.test调用方式完全错了——x = test$Ideology, y = test$treatment是把treatment当作另一个连续变量做双样本检验,而非用它作为分组变量拆分Ideology。这就导致每次检验的都是Ideology和treatment两个变量的差异,而非两组Ideology的组间差异,所以结果恒定不变。

修正步骤

  1. 正确调用t检验
    用公式接口(推荐)或手动拆分分组数据,让R按treatment的0/1分组比较Ideology:

    • 公式接口(最简洁):t.test(Ideology ~ treatment, data = test)
    • 手动拆分:t.test(x = test$Ideology[test$treatment == 1], y = test$Ideology[test$treatment == 0])
  2. 修复其他小问题

    • results数据框中列名是PValue,但你写的p_value大小写不匹配,会报错;
    • 显著性阈值用0.5不符合统计常规,一般用0.05。

修正后的完整代码

set.seed(17800)

differences <- c()
p_values <- c()

for (i in 1:5000) {
  test <- experiment_pool %>%
    mutate(treatment = sample(rep(c(0,1), length = n())))
  # 按treatment分组做Ideology的独立样本t检验
  t_test_result <- t.test(Ideology ~ treatment, data = test)
  # 提取处理组均值 - 对照组均值的差异
  differences[i] <- t_test_result$estimate[2] - t_test_result$estimate[1]
  p_values[i] <- t_test_result$p.value
}

results <- data.frame(Difference = differences, PValue = p_values) %>%
  mutate(sig_diff = if_else(PValue < 0.05, 1, 0))

补充说明

  • t.test(Ideology ~ treatment)会自动返回对照组(0)和处理组(1)的均值,顺序固定,所以用estimate[2] - estimate[1]得到处理组相对对照组的差异;
  • 修正后每次循环都会生成新的随机分组,t检验结果也会随之变化,不会再出现恒定值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 13:02:29