如何在 R 資料框中測試兩個分類列之間的顯著關係?


要測試 R 資料框中兩個分類列之間比例的顯著性,我們首先需要使用這些列找到列聯表,然後使用 chisq.test 應用卡方獨立性檢驗。例如,如果我們有一個名為 df 的資料框,其中包含兩個分類列,例如 C1 和 C2,那麼可以使用命令 chisq.test(table(df$C1,df$C2)) 對顯著關係進行檢驗。

示例

 線上演示

x1<-sample(LETTERS[1:4],20,replace=TRUE)
y1<-sample(letters[1:4],20,replace=TRUE)
df1<-data.frame(x1,y1)
df1

輸出

   x1 y1
1  D  a
2  B  d
3  D  d
4  B  d
5  A  a
6  A  b
7  B  c
8  D  d
9  C  d
10 D  c
11 C  a
12 D  c
13 D  a
14 A  a
15 B  d
16 A  c
17 C  d
18 A  d
19 C  b
20 D  a

示例

table(df1$x1,df1$y1)

輸出

   a  b  c  d
A  2  1  1  1
B  0  0  1  3
C  1  1  0  2
D  3  0  2  2

查詢 df1 中 x1 和 y1 列之間的顯著關係 -

示例

chisq.test(table(df1$x1,df1$y1))

輸出

   Pearson's Chi-squared test
data: table(df1$x1, df1$y1)
X-squared = 7.4464, df = 9, p-value = 0.5907
Warning message:
In chisq.test(table(df1$x1, df1$y1)) :
Chi-squared approximation may be incorrect

示例

 線上演示

x2<-sample(c("hot","cold"),20,replace=TRUE)
y2<-sample(c("summer","winter","spring"),20,replace=TRUE)
df2<-data.frame(x2,y2)
df2

輸出

    x2    y2
1  cold  winter
2  hot   winter
3  hot   winter
4  hot   spring
5  cold  summer
6  cold  summer
7  cold  spring
8  hot   winter
9  cold  summer
10 hot   spring
11 hot   winter
12 cold  winter
13 cold  winter
14 hot   summer
15 hot   winter
16 hot   summer
17 hot   summer
18 cold  summer
19 cold   spring
20 hot   summer

示例

table(df2$x2,df2$y2)

輸出

spring summer winter
cold 2 4 3
hot 2 4 5

查詢 df2 中 x2 和 y2 列之間的顯著關係 -

示例

chisq.test(table(df2$x2,df2$y2))

輸出

   Pearson's Chi-squared test
data: table(df2$x2, df2$y2)
X-squared = 0.30303, df = 2, p-value = 0.8594
Warning message:
In chisq.test(table(df2$x2, df2$y2)) :
Chi-squared approximation may be incorrect

更新於: 2021年3月17日

587 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告