fast function for generating bootstrap samples in matrix forms in R
Asked Answered
W

1

2

I have a matrix A, and I would like to draw samples from each column of A and construct new matrices. For example:

A = matrix(seq(1,9),3,3)

so to get the 1st bootstrap matrix, I would sample with replacement (3 times) from the first column of A, i.e. 1,2,3, sample with replacement (3 times) from the second column of A, i.e. 4,5,6, and sample with replacement (3 times) from the third column of A, i.e. 7,8,9. After that, I re-construct the 1st bootstrap matrix B1 by combining the three bootstrap vectors. I will repeat this procedure for B=199 times, so that bootstrap matrices B1,...,B199 will be available.

My question is, how can I make this program run faster? Which function should I use? I know apply involves essentially for loops so the speed is not guaranteed. How about do.call? Thanks!

Wentletrap answered 22/11, 2012 at 16:20 Comment(0)
I
5

You can use replicate and apply:

A <- matrix(seq(1,9),3,3)

B <- 199

replicate(B, apply(A, 2, sample, replace = TRUE))
Indiscipline answered 22/11, 2012 at 16:27 Comment(2)
thanks, but the use of sample is to sample without replacement. Here I hope to get bootstrap sample, so how can I pass replace=TRUE to the function?Wentletrap
I got it: replicate(B, apply(A, 2, function(s) sample(s,replace=TRUE))) will work :)Wentletrap

© 2022 - 2024 — McMap. All rights reserved.