R BootStrap Data Frame

Viewed 660
# Bootstrap 95% CI for R-Squared
library(boot)
# function to obtain R-Squared from the data
rsq <- function(formula, data, indices) {
  d <- data[indices,] # allows boot to select sample
  fit <- lm(formula, data=d)
  return(coef(fit))
}
# bootstrapping with 1000 replications
results <- boot(data=mtcars, statistic=rsq,
   R=1000, formula=mpg~wt+disp)

# get 95% confidence interval
boot.ci(results, type="bca")

Say you run this bootstrap and get 1000 estimates of the intercept, wt and disp variables and so then you want to put all estimates into the data frame.

dataframe = data.frame(results$t)

That will do it but how do you code it to make sure that the column names get the right variable names? I did it that way and it makes column names 'Var1' 'Var2' and 'Var3' but I would wish for them to be 'Intercept' 'wt' and 'weight' and I know I can change them to this; I am wondering how to automate it to make sure the columns get the right names from boot.

1 Answers

Here, we can make use of the names attribute from the 't0' component. When we have model objects (or any objects), it is better to check str to understand the structure of each of the components. This would help greatly in understanding the models and the components

str(results)
#List of 11
# $ t0       : Named num [1:3] 34.9606 -3.3508 -0.0177
#  ..- attr(*, "names")= chr [1:3] "(Intercept)" "wt" "disp"
# $ t        : num [1:1000, 1:3] 34.1 37.2 37.3 33.8 34.7 ...
# $ R        : num 1000
# ...

The output is a list and extracting the list components can be done with $ or [[ (for multiple elements, [)

The t element is a matrix with no dimnames attribute while t0 have the "names" attribute. So, if we want to rename the data.frame converted matrix, just extract the names

df1 <- data.frame(results$t)
names(df1) <- names(results$t0)
Related