單一母體比例檢定

R 中的假設檢定

Richie Cotton

Data Evangelist at DataCamp

第 1 章重點回顧

  • 關於未知母體比例的主張可行嗎?
  • 使用重抽樣(bootstrap)分配計算樣本統計量的標準誤。
  • 用此計算標準化檢定統計量,…
  • 接著用它計算 p 值,…
  • 再用它判斷哪個假設較合理。
  • 這裡我們將不靠重抽樣分配來計算檢定統計量。
R 中的假設檢定

比例的標準化檢定統計量

$p$: 母體比例(未知的母體參數)

$\hat{p}$: 樣本比例(樣本統計量)

$p_{0}$: 假設的母體比例

$$ z = \frac{\hat{p} - \text{mean}(\hat{p})}{\text{standard error}(\hat{p})} = \frac{\hat{p} - p}{\text{standard error}(\hat{p})} $$

在 $H_{0}$ 為真時,$p = p_{0}$,因此

$$ z = \dfrac{\hat{p} - p_{0}}{\text{standard error}(\hat{p})} $$

R 中的假設檢定

更容易的標準誤計算

$SE(\bar{x}_{\text{child}} - \bar{x}_{\text{adult}}) \approx \sqrt{\dfrac{s_{\text{child}}^2}{n_{\text{child}}} + \dfrac{s_{\text{adult}}^2}{n_{\text{adult}}}}$

$SE_{\hat{p}} = \sqrt{\dfrac{p_{0}*(1-p_{0})}{n}}$

假設 $H_{0}$ 為真,

$z = \dfrac{\hat{p} - p_{0}}{\sqrt{\dfrac{p_{0}*(1-p_{0})}{n}}}$

這只用到樣本資訊($\hat{p}$ 與 $n$)以及假設的參數($p_{0}$)。

R 中的假設檢定

為何用 z 不用 t?

$t = \dfrac{(\bar{x}_{\text{child}} - \bar{x}_{\text{adult}})}{\sqrt{\dfrac{s_{\text{child}}^2}{n_{\text{child}}} + \dfrac{s_{\text{adult}}^2}{n_{\text{adult}}}}}$

  • $s$ 由 $\bar{x}$ 計算而得,所以 $\bar{x}$ 同時用來估計母體平均與母體標準差。
  • 這會增加對母體參數估計的不確定性。
  • t 分配的尾部比常態分配更厚。
  • 因此更保守。
  • $\hat{p}$ 只出現在分子,所以用 z 分數即可。
R 中的假設檢定

Stack Overflow 年齡分類

$H_{0}$:未滿 30 歲的 SO 使用者比例等於 0.5。

$H_{A}$:未滿 30 歲的 SO 使用者比例不等於 0.5。

alpha <- 0.01
stack_overflow %>% 
  count(age_cat)
# A tibble: 2 x 2
  age_cat         n
  <chr>       <int>
1 At least 30  1050
2 Under 30     1216
R 中的假設檢定

z 所需變數

p_hat <- stack_overflow %>%
  summarize(prop_under_30 = mean(age_cat == "Under 30")) %>%
  pull(prop_under_30)
0.5366
p_0 <- 0.50
n <- nrow(stack_overflow)
2266
R 中的假設檢定

計算 z 分數

$z = \dfrac{\hat{p} - p_{0}}{\sqrt{\dfrac{p_{0}*(1-p_{0})}{n}}}$

numerator <- p_hat - p_0
denominator <- sqrt(p_0 * (1 - p_0) / n)
z_score <- numerator / denominator
3.487
R 中的假設檢定

計算 p 值

常態分配的 CDF。小於 -2 的部分為紅色,大於 2 的部分為綠色。 左尾(「小於」)

p_value <- pnorm(z_score) 

右尾(「大於」)

p_value <- pnorm(z_score, lower.tail = FALSE)

雙尾(「不等於」)

p_value <- pnorm(z_score) + 
  pnorm(z_score, lower.tail = FALSE)
p_value <- 2 * pnorm(z_score)
0.000244
p_value <= alpha
TRUE
R 中的假設檢定

一起來練習吧!

R 中的假設檢定

Preparing Video For Download...