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

使用purrr结合expand.grid按分组变量循环执行t检验并精简代码

Solution

Here's a scalable, tidyverse-friendly approach to run your t-tests across all combinations of grouping variable z and predictors x1-x4, and collect the results in a single tidy dataframe:

Step 1: Load Required Libraries

First, make sure you have these packages installed and loaded:

library(tidyverse)
library(broom)

Step 2: Example Data (for testing)

If you don't have your data ready, here's a reproducible example to work with:

set.seed(123)
df <- tibble(
  y = rnorm(100),
  x1 = rnorm(100),
  x2 = rnorm(100),
  x3 = rnorm(100),
  x4 = rnorm(100),
  z = sample(c(0, 1), 100, replace = TRUE)
)

Step 3: Run Scalable T-Tests

This code will automatically handle any number of predictors (just add more to the predictors vector) and any number of levels in z:

# Define your list of predictor variables
predictors <- c("x1", "x2", "x3", "x4")

# Create all combinations of z levels and predictors
test_combinations <- crossing(
  z_group = unique(df$z),
  predictor = predictors
)

# Run tests and collect tidy results
tidy_test_results <- test_combinations %>%
  mutate(
    test_output = map2(
      z_group, predictor,
      ~ df %>%
        filter(z == .x) %>%
        # Choose one of the following test options:
        # Option 1: Pearson correlation t-test (tests association between y and x)
        do(tidy(cor.test(.$y, .[[.y]], method = "pearson"))) %>%
        # Option 2: Linear regression t-test (tests slope of y ~ x)
        # do(tidy(lm(y ~ !!sym(.y), data = .)))
    )
  ) %>%
  unnest(test_output) %>%
  # Rename columns for clarity
  rename(group_z = z_group, predictor_var = predictor)

How It Works:

  • crossing() generates every possible pair of z levels and predictor variables—this is what makes the code scalable (add more predictors to the vector, and it will automatically create new combinations).
  • map2() iterates over each combination: it filters the data to the current z group, then runs the t-test (either correlation or linear regression) between y and the current predictor.
  • broom::tidy() converts the messy test output into a structured dataframe.
  • unnest() stacks all the individual test results into one single dataframe.

Output:

Your final tidy_test_results dataframe will have columns like group_z, predictor_var, estimate, statistic, p.value, conf.low, conf.high—all the key stats from each t-test, organized neatly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:36:22