I am looking for a short and efficient method to run individual ANOVA analysis on each level of a factor. What I currently have, I think, is redundant and clutters the work space. Let's say I have the following:
Letter Number Question
A 1 1
A 2 1
A 3 1
B 1 1
B 2 1
B 3 1
C 1 1
C 2 1
C 3 1
I could run the following code to split the data frame into subsets A, B, and C:
> list2env(split(data, data$Letter), globalenv())
> ANOVA.A <- aov(Question~Number, data=A)
> ANOVA.B <- aov(Question~Number, data=B)
> ANOVA.C <- aov(Question~Number, data=C)
While this provides me with the required results, it clutters the workspace. My actual data set is far larger, so I am seeking something simpler and more elegant.
Using base lapply
:
lapply(split(df, df$Letter), aov, formula=Question ~ Number)
Alternatively using dplyr
:
library(dplyr)
obj <- df %>% group_by(Letter) %>% do(model = aov(Question~Number, data = .))
obj$model
Using data.table
:
library(data.table)
df <- as.data.table(df)
df[, list(Model = list(aov(Question ~ Number))), keyby = Letter]$Model
来源:https://stackoverflow.com/questions/28122162/perform-an-anova-for-each-individual-level-of-a-factor-in-r