"只有一种检验"框架

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() 选择要检验的变量。

  • 对于双样本检验,用 response ~ explanatory
  • 对于单样本检验,用 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() 声明原假设类型。

  • 双样本检验:用 "independence""point"
  • 单样本检验:用 "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 中的假设检验

Passons à la pratique !

R 中的假设检验

Preparing Video For Download...