卡方独立性检验

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 中的假设检验

Passons à la pratique !

R 中的假设检验

Preparing Video For Download...