Search code examples
rloopsfor-loopt-test

Loop t.test over columns in R


I have a numeric and several binary variables. I'd like to loop a ttest for each binary variable.

Using

library(boot)
df <- nuclear

both

  t.test(df$cost, df[6])

and

  t.test(df$cost, df$pr)

give me the same result. However, If I want to loop it, I'll do the following:

for(i in 6:9) {
  t.test(df$cost, df[i])
}

which then doesnt give any output.

How can I get a result here and why is this output supressed?


Solution

  • Solution using lapply:

    library(boot)
    
    df <- nuclear 
    
    
    list_of_ttests <- lapply(6:9, function(i){
        t.test(df[,1], df[,i])
    })
    

    This generates a list of t-tests and saves them to a list.