Introduction
The bootstrap is a non-parametric statistical method that relies on resampling from the sample itself to estimate the distribution of a statistic. It is particularly useful when the theoretical distribution of the statistic is unknown or hard to derive analytically. Through repeated sampling with replacement, it allows inference about the population from a single available sample. This article explains the method and how it is applied in R, with an example on simulated data.
The idea behind the bootstrap
Take the simulated data of the cohort of 800 patients with type 2 diabetes used in a previous article. In these data the median HbA1c is 6.9%. If the same study were repeated on a new sample of 800 patients from the same population, the estimated median would probably not be exactly 6.9%, but would differ slightly from it.
The question, then, is how much the estimate of the median can vary from sample to sample. In practice, however, we usually have only one sample and cannot actually repeat the study thousands of times.
The core idea of the bootstrap, proposed by Efron, is to use the available sample as an approximation of the population. Since the 800 patients are the best information available about the population, we can resample from them in the same way we would sample from the population.
The procedure resembles a draw. The 800 individuals of the original sample are placed in an urn. One individual is picked at random, recorded and returned to the urn before the next pick. The procedure continues until 800 picks have been made.
This creates a new sample of size 800, in which some patients may appear more than once while others may not appear at all. This new sample is called a bootstrap sample. Sampling with replacement is what allows the bootstrap samples to differ in composition from one another, even though they all come from the same original sample.
Next, the median HbA1c is computed in each bootstrap sample. The procedure is repeated many times, for example 5,000 or 10,000 times. The resulting medians form the bootstrap distribution of the median. This distribution is used as an approximation of the theoretical sampling distribution, the one that could be observed if the study were repeated many times in the real population.
The standard deviation of the bootstrap medians is a bootstrap estimate of the standard error of the original median. In addition, in the percentile bootstrap, the 2.5th and 97.5th percentiles of the bootstrap distribution are used as the lower and upper limits of an approximate 95% confidence interval.
The whole procedure is shown in the diagram below.

Application to simulated data
The data from here are used, in their complete form before missing values were introduced.
rSimulating the cohort31 lines
library(tidyverse); library(boot); library(patchwork)
theme_set(theme_minimal(base_family = "sans", base_size = 12) +
theme(panel.grid.minor = element_blank(), plot.title.position = "plot"))
navy <- "#1F2A44"; pink <- "#D5487F"; grey <- "#8A93A6"
set.seed(2026)
n <- 800
d <- tibble(
age = round(rnorm(n, 64, 10)),
sex = factor(sample(c("F", "M"), n, replace = TRUE)),
dm_years = round(rexp(n, 1 / 8)),
education = factor(sample(c("primary", "secondary", "tertiary"), n, replace = TRUE,
prob = c(0.35, 0.45, 0.20)),
levels = c("primary", "secondary", "tertiary")),
smoking = factor(rbinom(n, 1, plogis(-1.2 - 0.5 * (education == "tertiary"))),
labels = c("no", "yes")),
bmi = round(rnorm(n, 30, 5), 1),
sbp = round(128 + 0.5 * (age - 64) + 0.7 * (bmi - 30) + rnorm(n, 0, 13)),
ldl = round(rnorm(n, 105, 30)),
egfr = round(pmax(15, 95 - 0.9 * (age - 64) - 1.2 * dm_years + rnorm(n, 0, 14))),
hba1c = round(6.4 + 0.07 * dm_years + 0.02 * (age - 64) + 0.03 * (bmi - 30) + rnorm(n, 0, 1.0), 1)
)
d_obs <- d |>
mutate(
ldl = if_else(runif(n) < 0.08, NA, ldl), # MCAR
hba1c = if_else(runif(n) < plogis(-2.4 + 0.08 * (age - 64) + 0.12 * dm_years), # MAR: ηλικία, έτη από διάγνωση
NA, hba1c),
smoking = if_else(runif(n) < plogis(-2.8 + 1.3 * (education == "primary")), # MAR: μόρφωση
NA, smoking),
egfr = if_else(runif(n) < plogis(-2.0 - 0.06 * (egfr - 75)), NA, egfr) # MNAR: η ίδια η τιμή
)In base R
Before using any package, the procedure is written once with base R functions, to show that it contains nothing more than what was described. The goal is the 95% confidence interval of the median HbA1c.
rBootstrapping the median with 2,000 replicates11 lines
set.seed(2026)
B <- 2000
boot_medians <- replicate(B, {
idx <- sample(n, n, replace = TRUE)
median(d$hba1c[idx])
})
tibble(estimate = median(d$hba1c),
se_boot = sd(boot_medians),
ci_low = quantile(boot_medians, 0.025),
ci_high = quantile(boot_medians, 0.975)) |>
mutate(across(everything(), ~ round(.x, 3)))# A tibble: 1 × 4
estimate se_boot ci_low ci_high
<dbl> <dbl> <dbl> <dbl>
1 6.9 0.043 6.8 7Each line corresponds to one step of the description. sample(n, n, replace = TRUE) is the draw with replacement and returns 800 patient positions, some repeated. median(d$hba1c[idx]) computes the median in the patients drawn. replicate(B, ...) repeats the previous two 2,000 times and stores the 2,000 medians. From these, sd() gives the bootstrap standard error and quantile() the confidence interval. The number of replicates, here 2,000, is not a parameter of the method but a matter of computational precision. More replicates stabilise the ends of the interval and do not narrow it, since its width is set by the data and not by B. For a standard error a few hundred are enough; for percentiles and intervals at least 2,000 are recommended, and in publications often 10,000.
rPlot of the procedure34 lines
set.seed(7)
orig <- tibble(x = d$hba1c, y = runif(n, 0, 1))
p_orig <- ggplot(orig, aes(x, y)) +
geom_point(colour = navy, alpha = 0.35, size = 0.9) +
geom_vline(xintercept = median(d$hba1c), colour = navy, linewidth = 0.7) +
scale_y_continuous(NULL, breaks = NULL) +
labs(x = "HbA1c (%)", title = "Αρχικό δείγμα") +
theme(plot.title = element_text(size = 11))
resamples <- map_dfr(1:3, function(b) {
idx <- sample(n, n, replace = TRUE)
tibble(b = paste("Bootstrap δείγμα", b), x = d$hba1c[idx], y = runif(n, 0, 1),
dup = duplicated(idx) | duplicated(idx, fromLast = TRUE))
})
meds <- resamples |> group_by(b) |> summarise(m = median(x))
p_res <- ggplot(resamples, aes(x, y)) +
geom_point(aes(colour = dup), alpha = 0.45, size = 0.9) +
geom_vline(data = meds, aes(xintercept = m), colour = pink, linewidth = 0.7) +
facet_wrap(~ b, ncol = 1) +
scale_colour_manual(values = c(`FALSE` = navy, `TRUE` = pink), guide = "none") +
scale_y_continuous(NULL, breaks = NULL) +
labs(x = "HbA1c (%)") +
theme(strip.text = element_text(size = 9, hjust = 0))
ci <- quantile(boot_medians, c(0.025, 0.975))
p_hist <- ggplot(tibble(m = boot_medians), aes(m)) +
geom_histogram(binwidth = 0.05, fill = alpha(pink, 0.35), colour = NA) +
geom_histogram(data = tibble(m = boot_medians[boot_medians >= ci[1] & boot_medians <= ci[2]]),
binwidth = 0.05, fill = pink, colour = NA) +
geom_vline(xintercept = median(d$hba1c), colour = navy, linewidth = 0.7) +
labs(x = "bootstrap διάμεσος HbA1c (%)", y = "πλήθος", title = "2.000 bootstrap διάμεσοι") +
theme(plot.title = element_text(size = 11))
p_orig + p_res + p_hist + plot_layout(widths = c(1, 1, 1.2))
In the three middle samples the pink dots are the patients drawn more than once and the pink vertical line is the median of that sample, which shifts slightly from sample to sample. The histogram on the right is the result of 2,000 such repetitions. Its spread is the uncertainty of the median.
The left and right plots show different things, and confusing them is the most common misunderstanding about the bootstrap. The left one is the distribution of the data, that is, how much patients differ from one another in HbA1c, and it spreads from about 4% to 10%. The right one is the distribution of the estimate, that is, how much the median would differ from study to study, and it spreads over a few tenths of a unit. The confidence interval concerns the second. It does not mean that 95% of patients have an HbA1c inside it, but that the population median lies inside it with 95% confidence.
Using the boot package
In practice the boot package (Canty & Ripley) is used, which automates the repetition and, above all, computes the confidence intervals correctly, which are not always the simple percentiles. All the user has to write is a function with two arguments, the data and a vector of positions idx, that returns the statistic computed on the rows idx. boot() takes care of generating the idx with replacement and calling the function R times.
median_fun <- function(data, idx) median(data$hba1c[idx])
set.seed(2026)
b <- boot(data = d, statistic = median_fun, R = 2000)
bORDINARY NONPARAMETRIC BOOTSTRAP
Call:
boot(data = d, statistic = median_fun, R = 2000)
Bootstrap Statistics :
original bias std. error
t1* 6.9 0.0025 0.04309499boot.ci(b, type = c("norm", "basic", "perc", "bca"))BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
Based on 2000 bootstrap replicates
CALL :
boot.ci(boot.out = b, type = c("norm", "basic", "perc", "bca"))
Intervals :
Level Normal Basic
95% ( 6.813, 6.982 ) ( 6.800, 7.000 )
Level Percentile BCa
95% ( 6.8, 7.0 ) ( 6.7, 6.9 )
Calculations and Intervals on Original Scale
Warning : BCa Intervals used Extreme Quantiles
Some BCa intervals may be unstableThe output of boot() has three columns. original is the estimate in the original sample. bias is the difference between the mean of the 2,000 bootstrap estimates and the original one and, when it is large relative to the standard error, warns that the statistic is biased. std. error is the bootstrap standard error.
boot.ci() returns four intervals, and the question always asked is which one to report. When the distribution of the bootstrap estimates is symmetric and centred on the original estimate, the four almost coincide and the choice does not matter. They differ when the distribution is skewed or shifted, and there the choice counts. perc is the simple percentiles, what was computed by hand, and is the easiest to explain but under-covers when there is bias. norm uses only the standard error and assumes a normal distribution, so it offers nothing beyond the classical formula. basic reflects the percentiles around the original estimate and corrects part of the bias. bca (bias-corrected and accelerated) corrects both bias and skewness and is the one recommended for publication (Efron & Tibshirani 1993, Carpenter & Bithell 2000). Its only cost is that it needs more replicates to stabilise, which is why the example uses 2,000 and not fewer.
Limitations of the method
The bootstrap rests on the assumption that the available sample is a satisfactory approximation of the population. When this assumption does not hold, the results may be unreliable.
A key problem arises in very small samples. With 15 or 20 observations, the sample may not capture the population distribution adequately. The bootstrap distributions and confidence intervals may then be too narrow, especially when the percentile method is used. The bootstrap reduces the need for specific parametric assumptions, but it does not remove the need for an adequate and representative sample.
There is also a problem when the observations are not independent, as with repeated measurements on the same patient, multicentre studies or time series. Resampling individual observations ignores this structure and can underestimate the standard error. In these cases the appropriate unit of independence, such as the patient or the centre, must be drawn, while for time series consecutive blocks are often used (block bootstrap).
Finally, the bootstrap does not correct selection bias. If the original sample does not represent the population to which we want to generalise the results, the same bias carries over to every bootstrap sample. The bootstrap can thus give a narrow and seemingly precise interval around a wrong value.
References
- Canty A, Ripley BD (2024). boot: Bootstrap R (S-Plus) Functions. R package.
- Carpenter J, Bithell J (2000). Bootstrap confidence intervals, when, which, what? A practical guide for medical statisticians. Statistics in Medicine, 19(9), 1141–1164.
- Davison AC, Hinkley DV (1997). Bootstrap Methods and their Application. Cambridge University Press.
- Efron B (1979). Bootstrap methods, another look at the jackknife. Annals of Statistics, 7(1), 1–26.
- Efron B, Tibshirani RJ (1993). An Introduction to the Bootstrap. Chapman & Hall.
- Hesterberg TC (2015). What teachers should know about the bootstrap, resampling in the undergraduate statistics curriculum. The American Statistician, 69(4), 371–386.


