Saja01
Saja01

Reputation: 55

How to combine lapply, t.test, leveneTest, if and else

I want to create a list of t-test results, where the appropriate corrections for unequal variances have been applied, if a levene-test indicated that they were necessary. Here are some example data.

#create dataset
set.seed(555)
data<- data.frame(group = rep(letters[1:2], each = 5),
                  var1 = rnorm(n = 10, mean = 1.2, sd = 1),
                  var2 = rnorm(n = 10, mean = 2.8, sd = .50))

>data
   group       var1     var2
1      a 1.89686907 2.696915
2      a 1.66000554 2.650026
3      a 0.03941319 2.932389
4      a 2.47693939 2.674999
5      a 0.14176879 2.650867
6      b 1.24219445 2.889152
7      b 1.87350165 2.576014
8      b 1.10712963 3.082120
9      b 1.00297421 2.502752
10     b 2.64126704 2.314156
> 

I found out how to create lists of levene-test results and t-test results (in this example, I assume equal variances for all t-tests).

levene.tests<-lapply(data[,c("var1","var2")],
                     function(x) leveneTest(x ~ data$group))
t.tests<-lapply(data[,c("var1","var2")],
                function(x) t.test(x ~ data$group, var.equal = TRUE))

And I also managed to use if and else, so R will choose the right type of test for me based on whether variances are equal or not for single variables.

#if else statement for var1 only
if (levene.tests$"var1"$"Pr(>F)"[1]<.05) {
  t.test(data$var1 ~ data$group, var.equal = FALSE)
} else {
  t.test(data$var1 ~ data$group, var.equal = TRUE)
}

What I am struggling with now is how to piece these codes together, so that I get the appropriate t-test result for all variables (in this case var1 and var2) in a list type object. Can anyone help out?

Upvotes: 1

Views: 610

Answers (2)

Ivan D.M.C.
Ivan D.M.C.

Reputation: 1

This is what I found that might help, using sapply function to the levene test you conducted (extracting "Pr(>F)" of the leveneTest):

levene.r <- sapply(levene.tests, `[`, c("Pr(>F)"))

levene.r
if needed, transpose levene.r
t(levene.r)

It should also work for the ttest (just need to look on str to extract the things you want form this object).

Upvotes: 0

akrun
akrun

Reputation: 887048

Here is one option where we loop over the names of 'levene.tests', extract the 'p.value', check if it is greater than or equal to 0.05 and use that logical value in 'var.equal of t.test

library(car)
out <- lapply(names(levene.tests), function(nm) {
    i1 <- levene.tests[[nm]]$"Pr(>F)"[1] >= 0.05
    t.test(data[[nm]]~ data$group, var.equal = i1)
   })

Upvotes: 4

Related Questions