R boot::boot(): function which returns mean and the used samples

Viewed 103

I'm using the boot() function from the boot package to bootstrap means from a population. The used function is:

boot_mean <- function(data, i){
  
  ds_m <- data[i]
  return(mean(ds_m))
  
}

Works like charm but now I want to adapt the boot_mean function so that I can get the samples which lead to the mean too. I tried:

library('boot')

boot_mean <- function(data, i){
  
  ds_m <- data[i]
  ds_m_mean <- mean(ds_m)
  rlist <- list("means" = ds_m_mean, "data" = ds_m)
  return(rlist)
  
}

dummy_data <- rnorm(500)
dummy_boot <- boot(dummy_data, boot_mean, R = 1000) 

Which results in an error:

Error in t.star[r, ] <- res[[r]] : incorrect number of subscripts on matrix

What's wrong here? How can I get the corresponding dataset to the bootstrapped mean?

1 Answers

From the documentation ?boot, describing the statistic argument.

A function which when applied to data returns a vector containing the statistic(s) of interest. ...

The boot() function only wants to deal with functions that output a single vector. Modifying your code to return a list of two elements means it won't work anymore. There's actually a little interesting oddity in R and the boot() function which means the code almost works if you set R=1 in the boot() call, but it's still wrong.

Fortunately for your purpose, the authors have already programmed the useful boot.array() function. It outputs a matrix with R rows and nrow(data) columns, indicating either how many times the jth individual was sampled for the ith bootstrap, or the indices of the sampled individuals. Getting the bootstrapped datasets can easily be found by selecting those individuals from the data. This can take a little while.

dats <- lapply(1:nrow(boot.array(dummy_boot)), 
    FUN = function(x) dummy_data[boot.array(dummy_boot, indices = TRUE)[x, ]])

If you have multiple columns of data you should add , , drop = FALSE

dats <- lapply(1:nrow(boot.array(dummy_boot)), 
    FUN = function(x) dummy_data[boot.array(dummy_boot, indices = TRUE)[x, ], , drop = FALSE])
Related