Run a for loop for an ANOVA analysis

Hello everyone,

I would be grateful if you could help me. I've imported a dataframe from Excel (9 columns, whose the first one contains the treatments of an experiment). I'd like to perform an ANOVA analysis (followed by a Tukey post hoc) of each variable (i.e. columns 2 to 9) by the first column of the treatmnents. I think I need a for loop for this instead of typing and carrying out 8 separeted tests (one for each combination "column-i with column-treatment").
I whish someone could give me tips to write the code.

Thanks in advance!

Giorgio

#Invent some data
DF <- data.frame(Treat = rep(LETTERS[1:4], 100, replace = TRUE),
                 A = rnorm(400),
                 B = rnorm(400),
                 C = rnorm(400),
                 D = rnorm(400),
                 E = rnorm(400),
                 F = rnorm(400),
                 G = rnorm(400),
                 H = rnorm(400))
#Make a list to store the results
FITS <- vector(mode = "list", length = 8)

for (i in 2:9){
  FITS[[i-1]] <- aov(DF[[i]] ~ DF[[1]])
}
FITS[[1]]
#> Call:
#>    aov(formula = DF[[i]] ~ DF[[1]])
#> 
#> Terms:
#>                  DF[[1]] Residuals
#> Sum of Squares    2.3112  444.9797
#> Deg. of Freedom        3       396
#> 
#> Residual standard error: 1.060041
#> Estimated effects may be unbalanced

Created on 2020-01-18 by the reprex package (v0.3.0)

2 Likes

Following up on @FJCC's approach, here is a purrr way of doing it without for loops:

library(tidyverse)

DF <- data.frame(Treat = rep(LETTERS[1:4], 100, replace = TRUE),
                 A = rnorm(400),
                 B = rnorm(400),
                 C = rnorm(400),
                 D = rnorm(400),
                 E = rnorm(400),
                 F = rnorm(400),
                 G = rnorm(400),
                 H = rnorm(400))

anova_results <- purrr::map(DF[,2:9], ~aov(.x ~ DF$Treat))
anova_results[[1]]
#> Call:
#>    aov(formula = .x ~ DF$Treat)
#> 
#> Terms:
#>                 DF$Treat Residuals
#> Sum of Squares    1.2864  331.4307
#> Deg. of Freedom        3       396
#> 
#> Residual standard error: 0.9148477
#> Estimated effects may be unbalanced

Created on 2020-01-18 by the reprex package (v0.3.0)

3 Likes

Thank you!!! Simple and effective.

Thank you!! This will be a precious tip for me.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.