Loop through several post hoc tests in R

2019-09-11 19:47发布

问题:

I have a dataframe called data. I have created a function that loop thorugh a list of variables and creates a linear model for each of them using lapply. This method is based on this post.

library(datasets)
testDF <- data.frame(Salaries)
#creates list of variables

varListTest <- names(testDF)[3:4] 

#creates a model for each of the variables in question
model<- lapply(varListTest, function(x) {
    lm(substitute(i~Rank, list(i = as.name(x))), data = testDF)}) 

#output model
lapply(model, summary) 

This works great. However, I would also like to run post-hoc tests in the same fashion, normally i would do this by running:

TukeyHSD(model)

This obviously won't work in this example, but I thought this would:

lapply(model, TukeyHSD)

But this returns:

no applicable method for 'TukeyHSD' applied to an object of class "lm"

What am I missing to make this work?

回答1:

Try:

lapply(model, function(m) TukeyHSD(aov(m)))

Here is a reproducible example:

testDF=iris


varListTest <- names(testDF)[1:3] 

#creates a model for each of the variables in question
model<- lapply(varListTest, function(x) {
  lm(substitute(i~Species, list(i = as.name(x))), data = testDF)})  


lapply(model, function(model) TukeyHSD(aov(model))) 

Which provide (truncated)

[[1]]
  Tukey multiple comparisons of means
    95% family-wise confidence level

Fit: aov(formula = model)

$Species
                      diff       lwr       upr p adj
versicolor-setosa    0.930 0.6862273 1.1737727     0
virginica-setosa     1.582 1.3382273 1.8257727     0
virginica-versicolor 0.652 0.4082273 0.8957727     0