如何在 R 中执行卡方检验来检验拟合优度?

r programmingserver side programmingprogramming更新于 2025/4/8 11:52:17

卡方检验是一种非参数检验,用于检验属于两个或多个类别的观测值是否服从特定的非正态分布。我们可以说,它将观测到的比例与预期概率进行比较。在 R 中,我们可以使用 chisq.test 函数执行此检验。查看以下示例以了解如何操作。

示例1

> x1<-sample(0:9,200,replace=TRUE)
> x1

输出

[1] 9 4 1 9 6 6 1 6 0 0 5 8 8 3 7 8 0 3 3 9 6 0 3 8 2 0 8 5 9 1 3 4 6 7 0 1 4
[38] 5 4 8 1 7 2 1 1 3 4 2 5 6 3 4 4 5 6 8 6 4 6 2 0 0 5 2 0 1 6 9 3 0 5 1 3 9
[75] 8 0 9 5 9 4 2 5 9 2 2 0 6 9 1 8 0 1 7 8 4 0 0 2 5 7 1 0 6 7 0 8 8 5 4 3 4
[112] 6 7 4 7 2 1 4 4 4 2 8 4 4 5 6 5 0 5 7 1 5 7 3 4 1 7 9 1 3 9 0 7 1 5 7 7 5
[149] 6 3 4 8 1 8 2 6 8 8 8 8 1 0 9 3 1 6 9 1 5 4 9 3 4 2 6 8 1 6 5 1 0 8 5 0 7
[186] 2 5 8 0 3 6 3 6 7 7 8 4 0 8 3

示例

> x1_table<-table(x1)
> x1_table

输出

x1
0 1 2 3 4 5 6 7 8 9
24 23 14 18 23 21 21 17 24 15
> chisq.test(x1_table,p=rep(0.1,10))

Chi-squared test for given probabilities

data: x1_table
X-squared = 6.3, df = 9, p-value = 0.7096

示例2

> x2<-c(14,25,17,14)
> p<-c(0.25,0.25,0.25,0.25)
> chisq.test(x2,p=p)

输出

Chi-squared test for given probabilities

data: x2
X-squared = 4.6286, df = 3, p-value = 0.2011

示例3

> x3<-rpois(200,5)
> x3

输出

[1] 3 2 4 4 5 4 9 5 8 8 2 9 5 0 7 3 3 4 8 4 3 7 3 7 3
[26] 2 4 2 7 5 7 5 2 5 3 6 4 6 4 5 7 7 6 7 5 9 6 6 4 1
[51] 6 4 5 7 8 7 3 3 2 7 3 6 7 7 1 2 1 3 7 6 5 5 3 4 5
[76] 2 5 5 3 5 5 7 5 3 10 8 6 3 6 10 6 3 2 3 3 7 4 6 2 5
[101] 3 5 3 2 4 4 3 4 7 5 6 7 9 4 4 6 4 10 4 2 4 0 4 3 6
[126] 5 5 1 4 5 5 6 6 5 1 7 2 4 6 6 5 2 2 5 7 2 6 5 3 8
[151] 2 5 4 4 4 3 4 4 9 4 7 2 6 2 3 5 5 3 8 5 5 9 4 4 7
[176] 5 6 6 5 6 3 3 8 5 5 9 6 9 8 4 8 3 2 6 6 4 6 6 7 6

示例

> x3_table<-table(x3)
> x3_table

输出

x3
0 1 2 3 4 5 6 7 8 9 10
2 5 20 29 33 37 30 23 10 8 3
> chisq.test(x3_table,p=rep(1/11,11))

Chi-squared test for given probabilities

data: x3_table
X-squared = 93.15, df = 10, p-value = 1.268e-15

示例4

> x4<-c(24,98,30,35,27,28)
> chisq.test(x4)

输出

Chi-squared test for given probabilities

data: x4
X-squared = 100.6, df = 5, p-value < 2.2e-16

示例5

> x5<-c(12,15,17,15,9,14)
> p<-c(0.1,0.1,0.2,0.2,0.1,0.1)
> chisq.test(x5,p)

输出

Pearson's Chi-squared test

data: x5 and p
X-squared = 3.75, df = 4, p-value = 0.4409

Warning message:
In chisq.test(x5, p) : Chi-squared approximation may be incorrect

示例6

> x6<-c(36,27,25,84,14,25,36,27,29)
> chisq.test(x6,p=rep(1/9,9))

输出

Chi-squared test for given probabilities

data: x6
X-squared = 94.812, df = 8, p-value < 2.2e-16

相关文章