Source: http://www.r-bloggers.com/analysis-of-variance-anova-for-multiple-comparisons/
用于多个比较的方差分析(ANOVA:Analysis of variance)
ANOVA模型能用于比较多个群组之间的均值,这里使用了参数(parametric)的方法,也就是假设这些群组符合Gaussian分布。以下为例子:
----------------------------------------------------
超市连锁店的经理想看看4个店面的耗电量(千瓦)是否相等。他在每个月底收集数据,持续了6个月,结果如下:
Store A: 65, 48, 66, 75, 70, 55
Store B: 64, 44, 70, 70, 68, 59
Store C: 60, 50, 65, 69, 69, 57
Store D: 62, 46, 68, 72, 67, 56
为了使用ANOVA来验证,我们必须首先验证homoskedasticity,也就是方差的同质性检验。R软件提供了两种检验方法:Bartlett检验,和Fligner-Killeen检验。
---------------------------------------------------
我们先看Bartlett检验。首先我们创建4个向量,然后再组合成一个向量:
a = c(65, 48, 66, 75, 70, 55) b = c(64, 44, 70, 70, 68, 59) c = c(60, 50, 65, 69, 69, 57) d = c(62, 46, 68, 72, 67, 56) dati = c(a, b, c, d)
groups = factor(rep(letters[1:4], each = 6))
bartlett.test(dati, groups) Bartlett test of homogeneity of variances data: dati and groups Bartlett's K-squared = 0.4822, df = 3, p-value = 0.9228
qchisq(0.950, 3) [1] 7.814728
-------------------------------------------------------------------
现在我们试着用Fligner-Killeen test来检测同质性。调用函数的方法和过程都类似:
a = c(65, 48, 66, 75, 70, 55) b = c(64, 44, 70, 70, 68, 59) c = c(60, 50, 65, 69, 69, 57) d = c(62, 46, 68, 72, 67, 56) dati = c(a, b, c, d) groups = factor(rep(letters[1:4], each = 6)) fligner.test(dati, groups) Fligner-Killeen test of homogeneity of variances data: dati and groups Fligner-Killeen:med chi-squared = 0.1316, df = 3, p-value = 0.9878
----------------------------------------------------------------------------------
已验证了4个群组的同质性,我们就可以来处理ANOVA模型了。首先拟合模型:
fit = lm(formula = dati ~ groups)
anova (fit) Analysis of Variance Table Response: dati Df Sum Sq Mean Sq F value Pr(>F) groups 3 8.46 2.82 0.0327 0.9918 Residuals 20 1726.50 86.33
因为p-value大于0.05,我们接受null hypothesis H0,即4个样本的均值统计相等。我们也可以比较计算的F-vaue和查表的F-value:
qf(0.950, 20, 3) [1] 8.66019
查表的F-value大于之前计算的F-value,因此我们接受null hypothesis。