Reference: https://tidymodels.github.io/rsample/articles/Working_with_rsets.html

library(tidyverse)
library(rsample)
library(janitor)
library(kableExtra)


# rename for convenience: 
df1.attrition <- attrition %>%   # factors that lead to employee attrition
      clean_names()

# str(df1.attrition)

Traditionally, the bootstrap has been primarily used to empirically determine the sampling distribution of a test statistic. Given a set of samples with replacement, a statistic can be calculated on each analysis set and the results can be used to make inferences (such as confidence intervals).

1) Rsample basics

https://tidymodels.github.io/rsample/articles/Basics.html  

What’s a resample?

We define a resample as the result of a two-way split of a data set. For example, when bootstrapping, one part of the resample is a sample with replacement of the original data. The other part of the split contains the instances that were not contained in the bootstrap sample

Here, each resample has class rsplit - see below.  

What’s an rset object?

The main class in the package (rset) is for a set or collection of resamples (aka rsplits). In 10-fold cross-validation, the set would consist of the 10 different resamples of the original data.  

Individual resamples are rsplit objects

There are two partitions that comprise an rsplit:

  1. “analysis” data: those that we selected in the resample. For a bootstrap, this is the sample with replacement. For 10-fold cross-validation, this is the 90% of the data. These data are often used to fit a model or calculate a statistic in traditional bootstrapping.

  2. “assessment” data: the section of the original data not covered by the analysis set. Often used to evaluate the performance of a model that was fit to the analysis data.    

2) mtcars example

set.seed(1)

 

Bootstrapping mtcars dataset:

bootstrap_resamples <- bootstraps(mtcars, 
                                  times = 10)

str(bootstrap_resamples, 
    max.level = 1)
## Classes 'bootstraps', 'rset', 'tbl_df', 'tbl' and 'data.frame':  10 obs. of  2 variables:
##  $ splits:List of 10
##  $ id    : chr  "Bootstrap01" "Bootstrap02" "Bootstrap03" "Bootstrap04" ...
##  - attr(*, "times")= num 10
##  - attr(*, "apparent")= logi FALSE
##  - attr(*, "strata")= logi FALSE
# 10 obs. of  2 variables: "splits" and "id" 

# examine result: 
bootstrap_resamples  # not very useful 
## # Bootstrap sampling 
## # A tibble: 10 x 2
##    splits          id         
##    <list>          <chr>      
##  1 <split [32/13]> Bootstrap01
##  2 <split [32/17]> Bootstrap02
##  3 <split [32/11]> Bootstrap03
##  4 <split [32/10]> Bootstrap04
##  5 <split [32/11]> Bootstrap05
##  6 <split [32/12]> Bootstrap06
##  7 <split [32/13]> Bootstrap07
##  8 <split [32/10]> Bootstrap08
##  9 <split [32/11]> Bootstrap09
## 10 <split [32/11]> Bootstrap10

 

Metadata about a split:

first_resample <- bootstrap_resamples$splits[[1]]  
first_resample  # <32/11/32>
## <32/13/32>

We learn the following about this particular resample:

  • 32 data points in the analysis set
  • 11 data points in the assessment set
  • 32 data points in the original data  

Data contained within the split:

first_resample$data  # first bootstrap sample data 
##                      mpg cyl  disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
## Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
## Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
## Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
## Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
## Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
## Merc 280C           17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
## Merc 450SE          16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3
## Merc 450SL          17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3
## Merc 450SLC         15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3
## Cadillac Fleetwood  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4
## Lincoln Continental 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4
## Chrysler Imperial   14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4
## Fiat 128            32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
## Honda Civic         30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
## Toyota Corolla      33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
## Toyota Corona       21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
## Dodge Challenger    15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2
## AMC Javelin         15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2
## Camaro Z28          13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4
## Pontiac Firebird    19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2
## Fiat X1-9           27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
## Porsche 914-2       26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
## Lotus Europa        30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
## Ford Pantera L      15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4
## Ferrari Dino        19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
## Maserati Bora       15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8
## Volvo 142E          21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2

 

Get just the analysis/assessment data:

analysis(first_resample)  %>% str  # get the "analysis"/training data 
## 'data.frame':    32 obs. of  11 variables:
##  $ mpg : num  19.2 21.4 14.3 21 21 15.8 15.2 17.8 15.2 32.4 ...
##  $ cyl : num  8 6 8 6 6 8 8 6 8 4 ...
##  $ disp: num  400 258 360 160 160 ...
##  $ hp  : num  175 110 245 110 110 264 150 123 180 66 ...
##  $ drat: num  3.08 3.08 3.21 3.9 3.9 4.22 3.15 3.92 3.07 4.08 ...
##  $ wt  : num  3.85 3.21 3.57 2.62 2.88 ...
##  $ qsec: num  17.1 19.4 15.8 16.5 17 ...
##  $ vs  : num  0 1 0 0 0 0 0 1 0 1 ...
##  $ am  : num  0 0 0 1 1 1 0 0 0 1 ...
##  $ gear: num  3 3 3 4 4 5 3 4 3 4 ...
##  $ carb: num  2 1 4 4 4 4 2 4 3 1 ...
assessment(first_resample) %>% str  # # get the "assessment"/test data 
## 'data.frame':    13 obs. of  11 variables:
##  $ mpg : num  22.8 18.1 24.4 16.4 17.3 10.4 14.7 33.9 13.3 27.3 ...
##  $ cyl : num  4 6 4 8 8 8 8 4 8 4 ...
##  $ disp: num  108 225 147 276 276 ...
##  $ hp  : num  93 105 62 180 180 215 230 65 245 66 ...
##  $ drat: num  3.85 2.76 3.69 3.07 3.07 3 3.23 4.22 3.73 4.08 ...
##  $ wt  : num  2.32 3.46 3.19 4.07 3.73 ...
##  $ qsec: num  18.6 20.2 20 17.4 17.6 ...
##  $ vs  : num  1 1 1 0 0 0 0 1 0 1 ...
##  $ am  : num  1 0 0 0 0 0 0 1 0 1 ...
##  $ gear: num  4 3 4 3 3 3 3 4 3 4 ...
##  $ carb: num  1 1 2 3 3 4 4 1 4 1 ...

     

3) Compare median monthly income between genders

 

boxplot:

p1.boxplots <- df1.attrition %>% 
      ggplot(aes(x = gender, 
                 y = monthly_income)) + 
      geom_boxplot() + 
      
      stat_summary(fun.y = mean, 
                   col = "firebrick", 
                   geom = "point") + 
      
      # data is positively skewed, so log it: 
      scale_y_log10(); p1.boxplots

 

Create resamples:

# bootstrapping attrition dataset 
boots.attrition <- bootstraps(df1.attrition, 
                              times = 500)

 

Compare medians between genders:

If we wanted to compare the genders, we could conduct a t-test or rank-based test (e.g. Wilcoxon’s). Instead, let’s use the bootstrap to see if there is a difference in the median incomes for the two groups. We need a simple function to compute this statistic on the resample

 

Function to calc difference in medians:

# fn definition: 
compare_male_female_stat <- function(splits, FUN = median, ...){
      
      #**************************************************************
      # inputs: 
      # > an "rsplit" object (i.e. single data point in the "splits" column that
      #     results from calling bootstraps() on a dataset) 
      # > function to call on the data (e.g. mean/median)
      #     DO NOT PUT QUOTES AROUND THE NAME OF THE FUNCTION! 
      
      # output: difference (male - female) in statistics for the male 
      #     group vs the female group 
      
      # example function call: 
      # median_diff_fn(split, mean)  # to find mean
      
      #**************************************************************
      
      # get the analysis data from the rsplit object: 
      df <- analysis(splits)
      
      # find median for Male: 
      male <- df %>% filter(gender == "Male") %>% 
            pull(monthly_income) %>% 
            FUN()
      
      # find median for Female: 
      female <- df %>% filter(gender == "Female") %>% 
            pull(monthly_income) %>% 
            FUN()
      
      
      return(male-female)
      
}


# fn test: 
compare_male_female_stat(boots.attrition$splits[[1]], 
                         mean)  # note that you can't put quotes around the function name
## [1] -227.3194

 

Map function across all splits:

# create a new col in the object boots.attrition: 

boots.attrition <- boots.attrition %>% 
  mutate(diff_median = map_dbl(boots.attrition$splits,  # each rsplit is passed to the function compare_male_female_stat(), and bound to the formal argument "splits" 
                               compare_male_female_stat))

boots.attrition
## # Bootstrap sampling 
## # A tibble: 500 x 3
##    splits             id           diff_median
##  * <list>             <chr>              <dbl>
##  1 <split [1.5K/540]> Bootstrap001       -288.
##  2 <split [1.5K/536]> Bootstrap002        122.
##  3 <split [1.5K/530]> Bootstrap003       -213 
##  4 <split [1.5K/530]> Bootstrap004         82 
##  5 <split [1.5K/549]> Bootstrap005       -106 
##  6 <split [1.5K/530]> Bootstrap006       -510.
##  7 <split [1.5K/512]> Bootstrap007       -284 
##  8 <split [1.5K/533]> Bootstrap008       -223 
##  9 <split [1.5K/521]> Bootstrap009       -372 
## 10 <split [1.5K/540]> Bootstrap010       -583 
## # ... with 490 more rows

 

Plot distribution of difference in medians

Even though you actually only have one sample for males and one sample for females, bootstrapping allows to to “pretend” that we actually have 500 samples of each, so that we could calculate the difference in means 500 times, and see what its distribution looks like.

boots.attrition %>% 
      ggplot(aes(x = diff_median))+
      geom_density() + 
      geom_vline(xintercept = 0, 
                 colour = "red") + 
      geom_vline(xintercept = boots.attrition$diff_median %>% mean, 
                 col = "grey70") + 
      labs(title = "diff in medians (male - female)") 

 

Interpretation of sampling distribution:

The sampling distribution is centered around -250 (grey line in the graph above). However, we know that the center of the sampling distribution of Y-bar = (median(male) - median(female)) is not necessarily the center of the population distribution of the parameter Y.

However, the variance of the sampling dist. also allows us to estimate variance of the population.

Putting these 2 pieces of info together (the center of sampling dist, and the variance of sampling dist.), we can construct a 95% confidence interval for the population parameter Y. CIs contructed in this way are guaranteed to capture the true population parameter 95% of the time.  

4) Compare means between genders:

boots.attrition <- boots.attrition %>% 
  mutate(diff_mean = map_dbl(boots.attrition$splits, 
                             compare_male_female_stat, 
                             FUN = mean))

boots.attrition 
## # Bootstrap sampling 
## # A tibble: 500 x 4
##    splits             id           diff_median diff_mean
##  * <list>             <chr>              <dbl>     <dbl>
##  1 <split [1.5K/540]> Bootstrap001       -288.   -227.  
##  2 <split [1.5K/536]> Bootstrap002        122.    164.  
##  3 <split [1.5K/530]> Bootstrap003       -213    -189.  
##  4 <split [1.5K/530]> Bootstrap004         82       7.45
##  5 <split [1.5K/549]> Bootstrap005       -106    -213.  
##  6 <split [1.5K/530]> Bootstrap006       -510.   -508.  
##  7 <split [1.5K/512]> Bootstrap007       -284    -194.  
##  8 <split [1.5K/533]> Bootstrap008       -223    -184.  
##  9 <split [1.5K/521]> Bootstrap009       -372    -495.  
## 10 <split [1.5K/540]> Bootstrap010       -583    -508.  
## # ... with 490 more rows
# plot diff: 
boots.attrition %>% 
      ggplot(aes(x = diff_mean))+
      geom_density() + 
      geom_vline(xintercept = 0, 
                 colour = "red") + 
      labs(title = "diff in means (male - female)")

 

5) Compare max between genders:

boots.attrition$diff_max <- map_dbl(boots.attrition$splits, 
                                     compare_male_female_stat, 
                                     FUN = max)


# plot diff: 
boots.attrition %>% 
      ggplot(aes(x = diff_max))+
      geom_density() + 
      geom_vline(xintercept = 0, 
                 colour = "red") + 
      labs(title = "diff in max (male - female)")

Question: Do the relative heights give an estimate of the prob that the highest paid person will be male vs female? E.g. if the male spike is 6 and the female one is 4, does this mean there’s a 60% chance that in the population as a whole, the highest paid person is male?