3

作为一个普通的 R 用户,我正在学习使用 python 进行分析,我从卡方开始并做了以下工作:

R

> chisq.test(matrix(c(10,20,30,40),nrow = 2))$p.value               # test1
[1] 0.5040359
> chisq.test(matrix(c(1,2,3,4),nrow = 2))$p.value                   # test2
[1] 1
Warning message:
In chisq.test(matrix(c(1, 2, 3, 4), nrow = 2)) :
  Chi-squared approximation may be incorrect
> chisq.test(matrix(c(1,2,3,4),nrow = 2),correct = FALSE)$p.value   # test3
[1] 0.7781597
Warning message:
In chisq.test(matrix(c(1, 2, 3, 4), nrow = 2), correct = FALSE) :
  Chi-squared approximation may be incorrect

Python

In [31]:
temp = scipy.stats.chi2_contingency(np.array([[10, 20], [30, 40]]))  # test1
temp[1] # pvalue
Out[31]:
0.50403586645250464
In [30]:
temp = scipy.stats.chi2_contingency(np.array([[1, 2], [3, 4]]))      # test2
temp[1] # pvalue
Out[30]:
0.67260381744151676

对于test1,我很满意,因为 python 和 R 的测试结果相似,但test2事实并非如此,因为 R 有参数correct,所以我将其从默认值更改,生成的 p 值不一样。

我的代码有什么问题吗?我应该“相信”哪一个?

更新01

感谢您的反馈。我知道卡方检验不应该用于值小于 5 的单元格,我应该使用 Fisher 精确检验,我担心的是为什么 R 和 Python 给出的 p 值差异如此之大。

4

1 回答 1

5

除了单元格计数 < 5 的问题,根据我的经验,统计测试的 R 和 Python 实现通常默认启用各种更正(应该改进基本方法)。关闭校正似乎使scipyp 值与 R 匹配:

scipy.stats.chi2_contingency(np.array([[1, 2], [3, 4]]), correction=False)

Out[6]: 
# p-val = 0.778159
(0.079365079365079388, 0.77815968617616582, 1, array([[ 1.2,  1.8],
        [ 2.8,  4.2]]))

这同样适用于 t 检验等,其中默认值可能是也可能不是假设方差相等。基本上,当您在统计软件之间匹配输出时遇到问题时,请开始查看默认参数以查看您是否应该启用或禁用这些调整。

于 2014-07-30T05:31:16.693 回答