Código
N <- 500 # Número de simulações
B <- 50 # Número de replicações do bootstrap
n <- 25
TrueMean <- 0
boot.df <- tibble(Iteração = integer(), SampleMean = numeric(), BootCI_Low = numeric(), BootCI_Hi = numeric(), Contain_TrueMean = numeric())
for (i in 1:N) {
#Amostra <- rnorm(n, mean = TrueMean, sd = 10)
Amostra <- runif(n, min = -5, max = 5)
Bootstrap <- matrix(sample(size = B*20, x = Amostra, replace = TRUE), nrow = B, ncol = n)
CI <- quantile(apply(Bootstrap, 1, mean), probs = c(.025, .975))
flag <- (TrueMean >= CI[1]) & (TrueMean <= CI[2])
boot.df[i,] <- c(i, mean(Amostra), CI[1], CI[2], flag)
}
Gráficos
boot.df %>% filter(row_number() <= n()) %>%
ggplot(aes(x = Iteração)) +
geom_linerange(aes(ymin = BootCI_Low, ymax = BootCI_Hi, color = as.factor(Contain_TrueMean)),size = .5) +
xlab("Iteração") + ylab("Intervalor de Confiança") + labs(colour = "Acerto", title="Bootstrap", size = 15) +
scale_colour_manual(labels =c("Não", "Sim"), values = c("red", "darkgreen")) +
geom_point(aes(y = SampleMean), color = "white", size = .5, alpha = .5)

boot.df %>%
filter(row_number() <= n()) %>%
mutate(Acumulado = cumsum(Contain_TrueMean)/row_number()) %>%
ggplot(aes(x = Iteração)) +
geom_line(aes(y=Acumulado)) +
geom_hline(yintercept = .95, color = "red") +
ylim(c(0, 1))
