对R中每个因子水平进行方差分析 [英] Perform an ANOVA for each individual level of a factor in R

查看:106
本文介绍了对R中每个因子水平进行方差分析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种简便有效的方法来对因子的每个水平进行独立的ANOVA分析.我认为,我目前所拥有的是多余的,并且使工作空间变得混乱.假设我有以下内容:

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

我可以运行以下代码将数据帧分为子集A,B和C:

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.

推荐答案

使用基本lapply:

lapply(split(df, df$Letter), aov, formula=Question ~ Number)

或者使用dplyr:

library(dplyr)
obj <- df %>% group_by(Letter) %>% do(model = aov(Question~Number, data = .))
obj$model

使用data.table:

library(data.table)
df <- as.data.table(df)
df[, list(Model = list(aov(Question ~ Number))), keyby = Letter]$Model

这篇关于对R中每个因子水平进行方差分析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆