Looping many one-sided ANOVA in R

喜夏-厌秋 提交于 2019-12-08 13:08:31

Since aov is based on lm you can cbind dependent variables on the LHS, which results in seperate models being run:

formula <- as.formula(paste0("cbind(", paste(names(iris)[-5], collapse = ","), ") ~ Species"))

fit <- aov(formula, data=iris)
summary(fit)
# Response Sepal.Length :
#             Df Sum Sq Mean Sq F value    Pr(>F)    
#Species       2 63.212  31.606  119.26 < 2.2e-16 ***
#Residuals   147 38.956   0.265                      
#---
#Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
# Response Sepal.Width :
#             Df Sum Sq Mean Sq F value    Pr(>F)    
#Species       2 11.345  5.6725   49.16 < 2.2e-16 ***
#Residuals   147 16.962  0.1154                      
#---
#Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
#</snip>

Alternatively, you can loop over the responses to create a list where each eleemnt corresponds to one model instead of the excellent answer from Roland which generates a 'single' model with multiple responses. This could be usefule if you want (in a later step) work with the generated models seperately:

responseList <- names(iris)[-5]
modelList    <- lapply(responseList, function(resp) {
                           mF <- formula(paste(resp, " ~ Species"))
                           aov(mF, data = iris)
                })

Then you could use lapply again to run the summary on the aov models:

lapply(modelList, summary)

As mentioned, the solution from Roland gives you a multiple responses model (class(fit)) whereas the solution above gives you a list of (single) response models. Whatever you prefer mainly depends on how you want to work with the result.

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