Einar
Einar

Reputation: 23

Looping many one-sided ANOVA in R

I would like to run 100 ANOVA for different numeric vectors.

My numeric vectors are (ruy, fjr, akf....) from my data.frame

aa=aov(data.frame$ruy~data.frame$Group)
anova(aa)
ab=aov(data.frame$fjr~data.frame$Group)
anova(ab)
ac=aov(data.frame$akf~data.frame$Group)
anova(ac)
.....
.....

My looping skills are poor so please be nice.

Upvotes: 2

Views: 4969

Answers (2)

thothal
thothal

Reputation: 20409

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.

Upvotes: 1

Roland
Roland

Reputation: 132989

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>

Upvotes: 2

Related Questions