如何在 R 中执行二因素方差齐性检验?


一般来说,我们可以说方差齐性检验是一种对比两个或更多变量的方差,并在它们之间存在显着差异时找出差异类型的检验。对于二因素方差齐性检验,最常用的检验之一是 Levene 检验,它可以借助 base R 中 car 包的 leveneTest 函数轻松完成。

考虑下面的数据框 −

示例

 在线演示

set.seed(151)
x1<-sample(c("C1","C2","C3"),20,replace=TRUE)
x2<-sample(c("S1","S2","S3","S4","S5"),20,replace=TRUE)
y<-rnorm(20,5,2)
df1<-data.frame(x1,x2,y)
df1

输出

  x1 x2   y
1 C2 S2 2.255857
2 C3 S5 1.726474
3 C3 S4 4.280697
4 C2 S3 7.402230
5 C2 S3 3.708252
6 C2 S4 3.978782
7 C2 S1 3.801754
8 C3 S3 6.091206
9 C2 S3 4.017412
10 C3 S3 5.383071
11 C3 S1 3.882945
12 C1 S5 6.845399
13 C1 S1 7.307996
14 C3 S4 2.255179
15 C1 S5 7.580363
16 C2 S5 7.309804
17 C2 S4 7.891359
18 C2 S3 5.522026
19 C3 S4 8.858292
20 C1 S1 3.800228

加载 car 包并在 df1 上执行 Levene 检验 −

library(car) leveneTest(y~x1*x2,data=df1) 
Levene's Test for Homogeneity of Variance (center = median)
Df F value Pr(>F)
group 9 1.5987 0.2374 10

让我们看看另一示例 −

示例

 在线演示

Age_group<-sample(c("First","Second"),20,replace=TRUE)
Ethnicity<-sample(c("Asian","NorthAmerican","Chinese","Japanese"),20,replace=TRUE)
Salary<-sample(20000:50000,20)
df2<-data.frame(Age_group,Ethnicity,Salary)
df2

输出

Age_group Ethnicity Salary
1 Second NorthAmerican 25678
2 Second Asian 34597
3 Second Chinese 49861
4 Second Chinese 37386
5 First Japanese 38426
6 Second NorthAmerican 45889
7 Second Asian 35033
8 Second NorthAmerican 46098
9 First Japanese 34070
10 Second Japanese 33618
11 First Japanese 35760
12 Second Chinese 33376
13 Second NorthAmerican 30630
14 First Asian 23820
15 Second Asian 40899
16 First Asian 35095
17 Second Chinese 43439
18 First Japanese 35641
19 Second Asian 41754
20 Second NorthAmerican 35337

在 df2 上执行 Levene 检验 −

leveneTest(Salary~Age_group*Ethnicity,data=df2)
Levene's Test for Homogeneity of Variance (center = median)
Df F value Pr(>F)
group 6 0.6593 0.6835 13

更新日期: 19-10-2020

1K+ 查看

开启你的 职业生涯

完成课程即可获得认证

开始
广告