0

I have a question regarding bootstrapping of a weighted mean.

Depending on how my data is structured, I sometimes want to bootstrap across columns and sometimes across rows.

In another post (bootstrap weighted mean in R), the following code was provided to bootstrap the weighted mean across columns:

library(boot)

samplewmean <- function(d, i, j) {
    d <- d[i, ]
    w <- j[i, ]
    return(weighted.mean(d, w))   
  }

results_qsec <- boot(data= mtcars[, 7, drop = FALSE], 
                     statistic = samplewmean, 
                     R=10000, 
                     j = mtcars[, 6 , drop = FALSE])

This works perfectly (check: weighted.mean(mtcars[,7], mtcars[,6]).

However, I now also want to bootstrap across rows, which I thought the following code would do:

samplewmean2 <- function(d, i, j) {
    d <- d[, i]
    w <- j[, i]
    return(weighted.mean(d, w))   
  }

results_qsec2 <- boot(data= mtcars[7,  , drop = FALSE], 
                     statistic = samplewmean2, 
                     R=10000, 
                     j = mtcars[6,  , drop = FALSE])

Unfortunately this is not working, and I don't know what I should change?

Many thanks in advance.

Anne
  • 19
  • 4
  • If you have 2 questions, you should probably separate them into 2 posts. You can have the second link back to the first as reference, but they should each be self-contained – camille Dec 09 '21 at 18:31

1 Answers1

0

Update

I think the easiest way is to get the row values into a vector and perform the bootstrap.

You could define your bootstrap-function like this:

samplewmean <- function(d,x, j) {
  return(weighted.mean(d[x], j[x]))
}

And then apply the bootstrap like this:

results_qsec2 <- boot(data= as.vector(t(mtcars[,  7, drop = FALSE])), 
                        statistic = samplewmean, 
                        R=100, 
                        j = as.vector(t(mtcars[,  6, drop = FALSE])))

If this is not what you want you can consider performing the bootstrap without the usage of any package. Then a good starting point would be the creation of a for-loop (or lapply, ...) using the resampling I suggested first:

elements2use <- sample(1:length(d), length(d), replace=T)
JKupzig
  • 1,226
  • 3
  • 13
  • Thanks for your reply! But could you please help out on the following aspect, as I'm not totally sure whether the code is correct? Because if I compare the "original" value given in the output of results_qsec2, it differs from using `weighted.mean(x=mtcars[,7], w=mtcars[,6])`, and I expected that those results would be the same? – Anne Dec 20 '21 at 09:10
  • See my updated answer now. – JKupzig Dec 29 '21 at 11:00