---
title: "bootstrapping"
author: "Paul Lewis"
date: "2024-02-14"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Generate a sample from a normal distribution
```{r}
mu <- 0.0
sigma <- 1.0
n <- 1000
x <- rnorm(n, mu, sigma)
plot(density(x), type="l", lwd=2, col="navy", main="Normal(0,1)", xlab="x", ylab="density")
rug(x)
```
# Calculate sample mean (should be close to true mean 0.0)
```{r}
mean(x)
```
# Calculate the (true) standard deviation of the mean ("standard error")
```{r}
sigma/sqrt(n)
```
# Now estimate the standard error by nonparametric bootstrapping
Obtain 1000 samples of size n with replacement and, for each, calculate the mean. Then obtain the sample standard deviation of the 1000 sample means.
```{r}
nreps <- 10000
y <- vector("numeric", nreps)
for (i in 1:nreps) {
xx <- sample(x, n, replace=TRUE)
y[i] <- mean(xx)
}
sd(y)
```