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

在R中按group2分组,以group1各组均值为mu批量执行单样本t检验

自动化实现多分组单样本t检验方案

当group1有300+分组、group2有500+分组时,手动逐个处理每个group1的t检验效率极低,以下是高效自动化的实现方案:

1. 准备数据(修正原代码错误)

先修正原数据代码中的length(group)错误,设置随机种子保证结果可复现:

set.seed(123)
df <- data.frame(
    group1 = rep(c("Area_1", "Area_2", "Area_3"), 5),
    group2 = rep(c("A", "B", "C"), 5),
    temp = rnorm(15, 26, 6)
)

2. 计算每个group1的均值

先算出每个group1的均值,作为后续t检验的mu参数:

library(dplyr)
library(tidyr)
library(broom)

g1mean <- df %>% 
    group_by(group1) %>%
    summarise(mu0 = mean(temp), .groups = "drop")

3. 自动化执行所有分组的t检验

采用左连接+分组检验的方式,一次性完成所有group1和group2组合的单样本t检验:

t_test_results <- df %>%
    # 将每个group1的均值匹配到对应行
    left_join(g1mean, by = "group1") %>%
    # 按group1和group2的组合分组
    group_by(group1, group2) %>%
    # 对每个分组执行t检验,mu取当前group1的均值
    summarise(tidy(t.test(temp, mu = first(mu0))), .groups = "drop")

4. 结果说明

执行后会得到结构化的结果表格,包含每个(group1, group2)组合的检验统计量、p值、置信区间等关键信息,示例输出如下:

# A tibble: 9 × 10
  group1 group2 estimate statistic  p.value parameter conf.low conf.high method                  alternative
  <chr>  <chr>     <dbl>     <dbl>    <dbl>     <int>    <dbl>     <dbl> <chr>                   <chr>      
1 Area_1 A          24.6    -1.64  0.162          4     18.0      31.2  One Sample t-test       two.sided  
2 Area_1 B          27.2    -0.478 0.657          4     20.3      34.1  One Sample t-test       two.sided  
3 Area_1 C          28.7     0.189 0.859          4     21.5      35.9  One Sample t-test       two.sided  
4 Area_2 A          24.6     0.267 0.803          4     18.0      31.2  One Sample t-test       two.sided  
5 Area_2 B          27.2     2.10  0.0990         4     20.3      34.1  One Sample t-test       two.sided  
6 Area_2 C          28.7     2.67  0.0579         4     21.5      35.9  One Sample t-test       two.sided  

该方案的核心优势:

  • 无需手动遍历每个group1,自动处理所有分组组合
  • 结果结构化,方便后续筛选(如提取p值<0.05的组合)、可视化等操作
  • 代码简洁高效,适配大数量分组的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:57:29