Compute bootstrap confidence intervals for any statistic FUN applied to vector x. Returns observed value and CI bounds.
boot_ci <- function(x, FUN = mean, R = 999, probs = c(0.025, 0.975), na.rm = TRUE) {
x <- if (na.rm) x[!is.na(x)] else x
obs <- FUN(x)
boot <- replicate(R, FUN(sample(x, replace = TRUE)))
ci <- quantile(boot, probs = probs)
list(observed = obs,
lower = ci[[1]],
upper = ci[[2]],
R = R)
}
# Example
boot_ci(rnorm(100), mean, R = 1000)