卡方獨立性檢定

R 中的假設檢定

Richie Cotton

Data Evangelist at DataCamp

重新檢視比例檢定

library(infer)
stack_overflow %>% 
  prop_test(
    hobbyist ~ age_cat,
    order = c("At least 30", "Under 30"),
    alternative = "two-sided",
    correct = FALSE
  )
# A tibble: 1 x 6
  statistic chisq_df   p_value alternative lower_ci upper_ci
      <dbl>    <dbl>     <dbl> <chr>          <dbl>    <dbl>
1      17.8        1 0.0000248 two.sided     0.0605    0.165
R 中的假設檢定

變數的獨立性

先前的假設檢定結果:有證據顯示 hobbyistage_cat 變數彼此相關。

如果反應變數的成功比例在解釋變數的各類別都相同,兩個變數就是「統計上獨立」。

1 「反應變數」與「解釋變數」的定義見「Introduction to Regression in R」第 1 章。
R 中的假設檢定

工作滿意度與年齡類別

stack_overflow %>% 
  count(age_cat)
# A tibble: 2 x 2
  age_cat         n
  <chr>       <int>
1 At least 30  1050
2 Under 30     1211
stack_overflow %>% 
  count(job_sat)
# A tibble: 5 x 2
  job_sat                   n
  <fct>                 <int>
1 Very dissatisfied       159
2 Slightly dissatisfied   342
3 Neither                 201
4 Slightly satisfied      680
5 Very satisfied          879
R 中的假設檢定

宣告虛無與對立假設

$H_{0}$:年齡類別與工作滿意度彼此獨立。

$H_{A}$:年齡類別與工作滿意度不獨立。

alpha <- 0.1
  • 檢定統計量記為 $\chi^{2}$。
  • 在獨立假設下,觀察到的結果與期望值相差多遠?
R 中的假設檢定

探索式視覺化:比例堆疊長條圖

ggplot(stack_overflow, aes(job_sat, fill = age_cat)) +
  geom_bar(position = "fill") +
  ylab("proportion")

以年齡類別著色的工作滿意度比例堆疊長條圖

R 中的假設檢定

使用 chisq_test() 的卡方獨立性檢定

library(infer)
stack_overflow %>% 
  chisq_test(age_cat ~ job_sat)
# A tibble: 1 x 3
  statistic chisq_df p_value
      <dbl>    <int>   <dbl>
1      5.55        4   0.235

自由度:

$(\text{反應類別數} - 1) \times (\text{解釋類別數} - 1)$

$(2 - 1) * (5 - 1) = 4$

R 中的假設檢定

對調變數?

ggplot(stack_overflow, aes(age_cat, fill = job_sat)) +
  geom_bar(position = "fill") +
  ylab("proportion")

以工作滿意度著色的年齡類別比例堆疊長條圖

R 中的假設檢定

卡方檢定的雙向對稱性

library(infer)
stack_overflow %>% 
  chisq_test(age_cat ~ job_sat)
# A tibble: 1 x 3
  statistic chisq_df p_value
      <dbl>    <int>   <dbl>
1      5.55        4   0.235

要問的是

變數 X 與 Y 是否獨立?

library(infer)
stack_overflow %>% 
  chisq_test(job_sat ~ age_cat)
# A tibble: 1 x 3
  statistic chisq_df p_value
      <dbl>    <int>   <dbl>
1      5.55        4   0.235

不是問

變數 X 是否獨立於變數 Y?

R 中的假設檢定

方向與尾部怎麼看?

args(chisq_test)
function (x, formula, response = NULL, explanatory = NULL, ...)
  • 觀察與期望次數的平方皆為非負。
  • 卡方檢定幾乎一律採用右尾。$^{1}$
1 左尾卡方檢定用於統計鑑識,以偵測擬合是否好得可疑(例如資料被捏造)。變異數的卡方檢定可以是雙尾。不過這些都是較少見的用途。
R 中的假設檢定

一起來練習吧!

R 中的假設檢定

Preparing Video For Download...