chisq.test() 函数中两个单元格为零时的卡方检验
Chi-square test when two cells are zero in the chisq.test() function
我在 R
中对 chisq.test() 进行了以下模拟测试
> dd <- data.frame(a=sample(1,size=100,replace=T),
+ group=sample(1:2,size=100,replace=T,prob = c(0.3,0.7)))
> dl <- data.frame(a=sample(1:2,size=100,replace=T),
+ group=sample(1:2,size =100,replace=T,prob = c(0.3,0.7)))
> table(dd)
group
a 1 2
1 32 68
> chisq.test(table(dd))
Chi-squared test for given probabilities
data: table(dd)
X-squared = 12.96, df = 1, p-value = 0.0003182
> table(dl)
group
a 1 2
1 21 33
2 9 37
> chisq.test(table(dl))
Pearson's Chi-squared test with Yates' continuity correction
data: table(dl)
X-squared = 3.5446, df = 1, p-value = 0.05974
我打算比较 group=1 和 group=2 之间的差异;计算在 dl 中正确完成。然而,在dd中,因为两组中的所有个体都包含100%的事件(所有个体都具有相同的aclass);两组之间应该没有差异(p=1),但是 chisq.test() 给出的 p 值为 0.0003,这应该是比较比例的差异(32% 对 68%)。但我真正想比较的是组内比例(100% 对 100%)。在这种情况下,我该如何正确使用 chisq.test?
将您的列转换为因子并指定它们可以采用的水平。这样就可以知道有空单元格了。
dd[,1] <- factor(dd[,1], levels = 1:2)
dd[,2] <- factor(dd[,2], levels = 1:2)
这给出了
> chisq.test(table(dd))
Pearson's Chi-squared test
data: table(dd)
X-squared = NaN, df = 1, p-value = NA
Warning message:
In chisq.test(table(dd)) : Chi-squared approximation may be incorrect
这可能不是您想要的,但比做每组概率相同的测试更正确。
我在 R
中对 chisq.test() 进行了以下模拟测试> dd <- data.frame(a=sample(1,size=100,replace=T),
+ group=sample(1:2,size=100,replace=T,prob = c(0.3,0.7)))
> dl <- data.frame(a=sample(1:2,size=100,replace=T),
+ group=sample(1:2,size =100,replace=T,prob = c(0.3,0.7)))
> table(dd)
group
a 1 2
1 32 68
> chisq.test(table(dd))
Chi-squared test for given probabilities
data: table(dd)
X-squared = 12.96, df = 1, p-value = 0.0003182
> table(dl)
group
a 1 2
1 21 33
2 9 37
> chisq.test(table(dl))
Pearson's Chi-squared test with Yates' continuity correction
data: table(dl)
X-squared = 3.5446, df = 1, p-value = 0.05974
我打算比较 group=1 和 group=2 之间的差异;计算在 dl 中正确完成。然而,在dd中,因为两组中的所有个体都包含100%的事件(所有个体都具有相同的aclass);两组之间应该没有差异(p=1),但是 chisq.test() 给出的 p 值为 0.0003,这应该是比较比例的差异(32% 对 68%)。但我真正想比较的是组内比例(100% 对 100%)。在这种情况下,我该如何正确使用 chisq.test?
将您的列转换为因子并指定它们可以采用的水平。这样就可以知道有空单元格了。
dd[,1] <- factor(dd[,1], levels = 1:2)
dd[,2] <- factor(dd[,2], levels = 1:2)
这给出了
> chisq.test(table(dd))
Pearson's Chi-squared test
data: table(dd)
X-squared = NaN, df = 1, p-value = NA
Warning message:
In chisq.test(table(dd)) : Chi-squared approximation may be incorrect
这可能不是您想要的,但比做每组概率相同的测试更正确。