Search code examples
rmatrixapplystatistics-bootstrap

Execute function multiple times and create matrix with results


The following code takes vector V1 and creates one bootstrapped sample called BV1. I would like to run that i times and place all the BVi vectors in matrix MV. Using a function of the apply family rather than a for loop if possible.

V1 <- c(0.18, 0.2, 0.24, 0.35, -0.22, -0.17, 0.28, -0.28, -0.14, 0.03, 0.87, -0.2, 0.06, -0.1, -0.72, 0.18, 0.01, 0.31, -0.36, 0.61, -0.16, -0.07, -0.13, 0.01, -0.09, 0.26, -0.14, 0.08, -0.62, -0.2, 0.3, -0.21, -0.11, 0.05, 0.06, -0.28, -0.27, 0.17, 0.42, -0.05, -0.15, 0.05, -0.07, -0.22, -0.34, 0.16, 0.34, 0.1, -0.12, 0.24, 0.45, 0.37, 0.61, 0.9, -0.25, 0.02)
BV1 <- sample(V1, length(V1), replace=TRUE) 

I will then use that matrix to calculate a distribution of the bootstrapped summary statistics. Thanks for your help.


Solution

  • We can use replicate to repeat the sample 'n' times and output as a matrix.

    replicate(4, sample(V1, length(V1), replace=TRUE))
    

    If we look at replicate

    function (n, expr, simplify = "array") sapply(integer(n), eval.parent(substitute(function(...) expr)), simplify = simplify)

    it uses sapply (so the OP's need for apply family of functions is covered)