Note: The type argument in generate() is automatically filled based on the entries for specify() and hypothesize(). It can be removed throughout the examples that follow. It is left in to reiterate the type of generation process being performed.

Data preparation

  • Two numeric - arr_delay, dep_delay
  • Two categories
    • season ("winter", "summer"),
    • day_hour ("morning", "not morning")
  • Three categories - origin ("EWR", "JFK", "LGA")
  • Sixteen categories - carrier

One numerical variable, one categorical (2 levels)

Calculate observed statistic

The recommended approach is to use specify() %>% calculate():

obs_chisq <- fli_small %>%
  specify(origin ~ season) %>% # alt: response = origin, explanatory = season
  calculate(stat = "Chisq")

The observed \(\chi^2\) statistic is 0.571898.

Or using chisq_test in infer

obs_chisq <- fli_small %>% 
  chisq_test(formula = origin ~ season) %>% 
  dplyr::select(statistic)

Again, the observed \(\chi^2\) statistic is 0.571898.

Or using another shortcut function in infer:

obs_chisq <- fli_small %>% 
  chisq_stat(formula = origin ~ season)

Lastly, the observed \(\chi^2\) statistic is 0.571898.

Randomization approach to \(\chi^2\)-statistic

chisq_null_distn <- fli_small %>%
  specify(origin ~ season) %>% # alt: response = origin, explanatory = season
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>%
  calculate(stat = "Chisq")
chisq_null_distn %>% visualize(obs_stat = obs_chisq, direction = "greater")

Calculate the randomization-based \(p\)-value

chisq_null_distn %>% 
  get_pvalue(obs_stat = obs_chisq, direction = "greater")
## # A tibble: 1 x 1
##   p_value
##     <dbl>
## 1   0.748

Theoretical distribution

fli_small %>%
  specify(origin ~ season) %>% 
  hypothesize(null = "independence") %>%
  # generate() ## Not used for theoretical
  calculate(stat = "Chisq") %>%
  visualize(method = "theoretical", obs_stat = obs_chisq, direction = "right")
## Warning: Check to make sure the conditions have been met for the
## theoretical method. {infer} currently does not check these for you.

Overlay appropriate \(\chi^2\) distribution on top of permuted statistics

fli_small %>%
  specify(origin ~ season) %>% # alt: response = origin, explanatory = season
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>%
  calculate(stat = "Chisq") %>% 
  visualize(method = "both", obs_stat = obs_chisq, direction = "right")
## Warning: Check to make sure the conditions have been met for the
## theoretical method. `infer` currently does not check these for you.

Compute theoretical p-value

fli_small %>% 
  chisq_test(formula = origin ~ season) %>% 
  dplyr::select(p_value) %>% 
  dplyr::pull()
## [1] 0.7513009