代码实现实例
案列:单因素方差分析中,你感兴趣的是比较分类因子定义的两个或多个组别中的因变量均值。以multcomp包中的cholesterol数据集为例,50个患者均接受降低胆固醇药物治疗(trt)五种疗法中的一种疗法。其中三种治疗条件使用药物相同,分别是20mg一天一次(1time)、10mg一天两次(2times)和5mg一天四次(4times)。剩下的两种方式(drugD和drugE)代表候选药物。
> library(multcomp)
> attach(cholesterol)
>
> # 统计各组样本大小
> table(trt)
trt
1time 2times 4times drugD drugE
10 10 10 10 10
>
> # 各组均值
> aggregate(response, by=list(trt), FUN=mean)
Group.1 x
1 1time 5.78197
2 2times 9.22497
3 4times 12.37478
4 drugD 15.36117
5 drugE 20.94752
>
> # 各组标准差
> aggregate(response, by=list(trt), FUN=sd)
Group.1 x
1 1time 2.878113
2 2times 3.483054
3 4times 2.923119
4 drugD 3.454636
5 drugE 3.345003
>
> # 进行方差分析
> fit <- aov(response ~ trt)
> summary(fit)
Df Sum Sq Mean Sq F value Pr(>F)
trt 4 1351.4 337.8 32.43 9.82e-13 ***
Residuals 45 468.8 10.4
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
代码实例实现
在双因素方差分析中,受试者被分配到两因子的交叉类别组中。以基础安装中的ToothGrowth数据集为例,随机分配60只豚鼠,分别采用两种喂食方法(橙汁或维生素C),各喂食方法中抗坏血酸含量有三种水平(0.5mg、1mg或2mg),每种处理方式组合都被分配10只豚鼠,牙齿长度为因变量。
> attach(ToothGrowth)
> table(supp, dose)
dose
supp 0.5 1 2
OJ 10 10 10
VC 10 10 10
>
> aggregate(len, by=list(supp, dose), FUN=mean)
Group.1 Group.2 x
1 OJ 0.5 13.23
2 VC 0.5 7.98
3 OJ 1.0 22.70
4 VC 1.0 16.77
5 OJ 2.0 26.06
6 VC 2.0 26.14
>
> aggregate(len, by=list(supp, dose), FUN=sd)
Group.1 Group.2 x
1 OJ 0.5 4.459709
2 VC 0.5 2.746634
3 OJ 1.0 3.910953
4 VC 1.0 2.515309
5 OJ 2.0 2.655058
6 VC 2.0 4.797731
>
> dose <- factor(dose)
#dose变量被转换为因子变量,这样aov()函数就会将它当做一个分组变量,而不是一个数值型协变量
> # condider interactive factor
> fit <- aov(len ~ supp*dose)
> summary(fit)
Df Sum Sq Mean Sq F value Pr(>F)
supp 1 205.4 205.4 15.572 0.000231 ***
dose 2 2426.4 1213.2 92.000 < 2e-16 ***
supp:dose 2 108.3 54.2 4.107 0.021860 *
Residuals 54 712.1 13.2
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1