Loop through several post hoc tests in R

好久不见. 提交于 2019-12-13 07:24:28

问题


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


来源:https://stackoverflow.com/questions/42270373/loop-through-several-post-hoc-tests-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!