user6106624
user6106624

Reputation:

Conduct Multiple T-Tests in R, Condensed

I wish to conduct multiple t-tests in R, without having to go through a copy-paste of each test. Each test will whether differences exist in the "Type" (whether "Left" or "Right") when looking at the "Level_#". Currently, I might have:

t.test(Level_1 ~ Type, alternative="two.sided", conf.level=0.99)
t.test(Level_2 ~ Type, alternative="two.sided", conf.level=0.99)

Type Level_1 Level_2 Level_3
Left      17      50      98
Right     18      65      65
Left      23       7      19
Left      65       7     100
Right     9       13      17

The issue is that I have hundreds of "Level_#" and would like to know how to automate this process and output a data frame of the results. My thought is to somehow incorporate an apply function.

Upvotes: 1

Views: 223

Answers (1)

DJV
DJV

Reputation: 4873

You can do it with using the tidyverse approach, and using the purrr and broom packages.

require(tidyverse)
require(broom)

df %>% 
  gather(var, level, -type) %>% 
  nest(-var) %>%
  mutate(model = purrr::map(data, function(x) { 
    t.test(level ~ type, alternative="two.sided", conf.level=0.99, 
           data = x)}), 
    value = purrr::map(model, tidy), 
    conf.low = purrr::map(value, "conf.low"),
    conf.high = purrr::map(value, "conf.high"),
    pvalue = purrr::map(value, "p.value")) %>% 
  select(-data, -model, -value)

Output:

     var  conf.low conf.high    pvalue
1 level1 -3.025393  4.070641 0.6941518
2 level2 -3.597754  3.356125 0.9260015
3 level3 -3.955293  3.673493 0.9210724

Sample data:

set.seed(123)
df <- data.frame(type = rep(c("left", "right"), 25), 
                 level1 = rnorm(50, mean = 85, sd = 5), 
                 level2 = rnorm(50, mean = 75, sd = 5), 
                 level3 = rnorm(50, mean = 65, sd = 5))

Upvotes: 1

Related Questions