Perform an ANOVA for each individual level of a factor in R

与世无争的帅哥 提交于 2019-12-09 07:20:23

问题


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.


回答1:


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

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