「唯一の検定」フレームワーク

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による仮説検定

関心変数の指定

左にデータフレームを表す格子。2列が強調表示。右向きの矢印の上に「specify」。その右に、強調された2列のみの格子。

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...