「只有一種檢定」框架

R 中的假設檢定

Richie Cotton

Data Evangelist at DataCamp

不平衡資料

stack_overflow_imbalanced %>% 
  count(hobbyist, age_cat, .drop = FALSE)
  hobbyist     age_cat    n
1       No At least 30    0
2       No    Under 30  191
3      Yes At least 30   15
4      Yes    Under 30 1025

若某些群體遠大於其他群體,樣本就是「不平衡」的。

R 中的假設檢定

假設

$H_{0}$:30 歲以下的愛好者比例與至少 30 歲的愛好者比例「相同」。

$H_{A}$:30 歲以下的愛好者比例與至少 30 歲的愛好者比例「不同」。

alpha <- 0.1

R 中的假設檢定

無論如何先做比例檢定

stack_overflow_imbalanced %>% 
  prop_test(
    hobbyist ~ age_cat,
    order = c("At least 30", "Under 30"),
    success = "Yes",
    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      2.79        1  0.0949 two.sided    0.00718   0.0217
R 中的假設檢定

圖形文法

圖形類型 base-R ggplot2
散佈圖 plot(, type = "p") ggplot() + geom_point()
折線圖 plot(, type = "l") ggplot() + geom_line()
直方圖 hist() ggplot() + geom_histogram()
盒鬚圖 boxplot() ggplot() + geom_boxplot()
長條圖 barplot() ggplot() + geom_bar()
圓餅圖 pie() ggplot() + geom_bar() + coord_polar()
R 中的假設檢定

假設檢定的文法

  • Allen Downey 的「There is only one test」框架。
  • 在 R 的 infer 套件中實作。
  • generate() 會建立模擬資料。
    • 計算成本高。
    • 對小樣本或不平衡資料較穩健。
null_distn <- dataset %>% 
  specify() %>% 
  hypothesize() %>% 
  generate() %>% 
  calculate()
obs_stat <- dataset %>% 
  specify() %>% 
  calculate()
get_p_value(null_distn, obs_stat)
1 Allen Downey 授課「Exploratory Data Analysis in Python」。
R 中的假設檢定

選定關注變數

左側是一個由儲存格組成的矩形網格,代表資料框。其中兩欄被反白。網格右側有「specify」字樣與向右箭頭。箭頭右側是只含那兩個反白欄位的另一個矩形網格。

R 中的假設檢定

specify()

specify() 用來選擇你要檢定的變數。

  • 2 樣本檢定用 response ~ explanatory
  • 1 樣本檢定用 response ~ NULL
stack_overflow_imbalanced %>%
  specify(hobbyist ~ age_cat, success = "Yes")
Response: hobbyist (factor)
Explanatory: age_cat (factor)
# A tibble: 1,231 x 2
  hobbyist age_cat    
  <fct>    <fct>      
1 Yes      At least 30
2 Yes      At least 30
3 Yes      At least 30
4 Yes      Under 30   
5 Yes      At least 30
6 Yes      At least 30
7 No       Under 30   
# ... with 1,224 more rows
R 中的假設檢定

hypothesize()

hypothesize() 用來宣告虛無假設的型式。

  • 2 樣本檢定用 "independence""point"
  • 1 樣本檢定用 "point"
stack_overflow_imbalanced %>%
  specify(hobbyist ~ age_cat, success = "Yes") %>%
  hypothesize(null = "independence")
Response: hobbyist (factor)
Explanatory: age_cat (factor)
Null Hypothesis: independence
# A tibble: 1,231 x 2
  hobbyist age_cat    
  <fct>    <fct>      
1 Yes      At least 30
2 Yes      At least 30
3 Yes      At least 30
4 Yes      Under 30   
5 Yes      At least 30
6 Yes      At least 30
7 No       Under 30   
# ... with 1,224 more rows
R 中的假設檢定

一起來練習吧!

R 中的假設檢定

Preparing Video For Download...