差異的區間

R 中的類別資料推論

Andrew Bray

Assistant Professor of Statistics at Reed College

兩變數的問題

男女相信的比例是否不同?

設 $p$ 為相信死後有生命的比例。

  • $H_{0} : p_{female} - p_{male} = 0$
  • $H_{A} : p_{female} - p_{male} \ne 0$
R 中的類別資料推論

男女對死後世界的看法是否不同?

ggplot(gss2016, aes(x = sex, fill = postlife)) +
  geom_bar()

ch2v2-postlife-barplot.png

R 中的類別資料推論

男女對死後世界的看法是否不同?

ggplot(gss2016, aes(x = sex, fill = postlife)) +
  geom_bar(position = "fill")

ch2v2-postlife-barplot-filled.png

R 中的類別資料推論

男女對死後世界的看法是否不同?

p_hats <- gss2016 %>%
  group_by(sex) %>%
  summarize(mean(postlife == "YES", na.rm = TRUE)) %>%
  pull()
d_hat <- diff(p_hats)
d_hat
0.1472851
R 中的類別資料推論

由 H0 產生資料

  • $H_{0} : p_{female} - p_{male} = 0$
  • 信仰來世與受試者性別之間沒有關聯。
  • 變數 postlife 與變數 sex 獨立。

以置換法產生資料

R 中的類別資料推論

男女對死後世界的看法是否不同?

gss2016 %>%
  specify(
    response = postlife, 
    explanatory = sex, 
    success = "YES"
  ) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1, type = "permute")
R 中的類別資料推論

男女對死後世界的看法是否不同?

gss2016 %>%
  specify(
    postlife ~ sex,  # this line is new
    success = "YES"
  ) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1, type = "permute")
Response: postlife (factor)
Explanatory: sex (factor)
Null Hypothesis:  independence 
# A tibble: 137 x 3
# Groups:   replicate [1]
   postlife sex    replicate
   <fct>    <fct>      <int>
 1 YES      FEMALE         1
 2 YES      MALE           1
 3 YES      FEMALE         1
 4 YES      MALE           1
 5 YES      MALE           1
 6 YES      FEMALE         1
 7 NO       FEMALE         1
R 中的類別資料推論

男女對死後世界的看法是否不同?

gss2016 %>%
  specify(
    postlife ~ sex, 
    success = "YES"
  ) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1, type = "permute")
Response: postlife (factor)
Explanatory: sex (factor)
Null Hypothesis:  independence 
# A tibble: 137 x 3
# Groups:   replicate [1]
   postlife sex    replicate
   <fct>    <fct>      <int>
 1 YES      FEMALE         1
 2 NO       MALE           1
 3 NO       FEMALE         1
 4 YES      MALE           1
 5 YES      MALE           1
 6 YES      FEMALE         1
 7 YES      FEMALE         1
R 中的類別資料推論

男女對死後世界的看法是否不同?

gss2016 %>%
  specify(postlife ~ sex, success = "YES") %>%
  hypothesize(null = "independence") %>%
  generate(reps = 500, type = "permute") %>%
  calculate(stat = "diff in props", order = c("FEMALE", "MALE"))
Warning message:
Removed 13 rows containing missing values.
R 中的類別資料推論

男女對死後世界的看法是否不同?

ggplot(null, aes(x = stat)) +
  geom_density() +
  geom_vline(xintercept = d_hat, color = "red")

這些資料顯示,性別在對死後生命的看法上存在差異。

ch2v2-density-plot.png

R 中的類別資料推論

一起來練習吧!

R 中的類別資料推論

Preparing Video For Download...