I am interested in finding the interval estimate of the mean of my response variable when the predictor variable is equal to a certain value, that is $E[Y|X=x]$. The point estimate for this statistic I am bootstrapping is $\hat{\beta_0} + \hat{\beta_1}x$.
However, I am having trouble calculating this statistic in the bootstrap replication. Here is what I have so far:
# load the libraries
library(purrr)
library(caret)
# set the seed
set.seed(872)
# load the data
boston = tibble::as_tibble(MASS::Boston)
# store the indices for use in 400 bootstrap resamples
index_resampling = createResample(boston$medv, times = 400)
# create a bootstrap resampling function
create_boot_resampling = function(data, idx) {
data[idx]
}
# fit the model
mod = lm(medv ~ rm, data = boston)
# calculate the bootstrap resamples
bootstrap_resample = map(index_resampling, ~create_boot_resampling(data = boston$medv, idx = .x))
# calculate the bootstrap replicates
bootstrap_replicate = unname(map_dbl(bootstrap_resample, ~predict(lm(.x ~ rm, data = boston), data.frame(rm = 4.929))))
# find the 90% confidence interval
quantile(bootstrap_replicate, probs = c(0.05, 0.950))
The medv is the response variable, and the rm is the predictor variable from the Boston dataset. I would like to find the point estimates of medv when rm is equal to 4.929, that is $\hat{\beta_0} + \hat{\beta_1} *$ 4.929. The code runs fine, but the confidence interval it outputs is incorrect. I have a feeling my error lies in the predict function used in the bootstrap replicate code, but I am unsure how to get the correct answer. Any hints or advice would be helpful!
library(boot); set.seed(872); myboot <- boot(MASS::Boston, function(DF, i) { predict(lm(medv ~ rm, data = DF[i,]), newdata = data.frame(rm = 4.929)) }, R = 400); boot.ci(myboot, conf = 0.9, type = "basic")
$\endgroup$bootstrap_replicate
asmap_dbl(bootstrap_resample, ~predict(lm(.x ~ rm, data = boston)
seems to take the y-values from your bootstrap samples but therm
values from the original undbootstrappedboston
. May that be the problem? Also: "output is incorrect" is a very vague error description. In future questions you should try to give mor details on how to spot that there is a problem. $\endgroup$set.seed(872); predict_medv <- function(rows){ regr <- lm(medv ~ rm, data = MASS::Boston[rows,]); predict(regr, newdata = data.frame(rm = 4.929)) }; bootstrapped <- replicate(4000, predict_medv(rows = sample(nrow(MASS::Boston), replace = TRUE))); quantile(bootstrapped, c(.05, .95))
$\endgroup$