如何使用 R 進行擬合優度卡方檢驗?


擬合優度的卡方檢驗是一種非引數檢驗,它用於測試落入兩個或更多類別的觀測值是否遵循特定分佈。我們可以說,它將觀測比例與期望機會進行比較。在 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

更新於: 2020 年 11 月 21 日

3K+ 瀏覽次數

開啟您的 職業生涯

完成課程並獲得認證

開始吧
廣告