library(tidyverse)
library(infer)   # Contains rep_slice_sample() function

# The same dragon sample and bootstrap distribution as in 01_Bootstrap_Distributions.R
########################################################################################

dragon_population <- read_csv("http://www.cknuckles.com/statsprogramming/data/dragon_data.csv")

set.seed(6)   # Same dragon sample and bootstrap results as in the book

dragon_sample <- dragon_population |>
  slice_sample(n = 75)       # sample of size 75

bootstrap_distribution_of_means <- dragon_sample |>
  rep_slice_sample(n=75 , reps=10000 ,  replace=TRUE) |>
  group_by(replicate) |>
  summarize(resample_mean = mean(wingspan))


# Example - Bootstrap CI for a Mean - SE Method
########################################################################################

# 95% CI using bootstrap distribution SE
SE <- .231
z_alpha2 <- 1.96   # 95% CI
c(6.96 - z_alpha2*SE, 6.96 + z_alpha2*SE)


# Example - Bootstrap CI for a Mean - Percentile Method
########################################################################################

# 95% CI - from the 2.5th percentile to the 97.5th percentile of the bootstrap distribution
quantile(bootstrap_distribution_of_means$resample_mean, c(.025,.975))


# For Comparison - Theory-Based 95% CI using T distribution
########################################################################################

s <- 2.0049          # from dragon sample
SE <- s/sqrt(75)     # CLT
t_alpha2 <- qt(.975, df=74)
c(6.96 - t_alpha2*SE, 6.96 + t_alpha2*SE)
