I have used replicate()
to produce a list of n_iter
elements. A minimal working example with hacked code follows. I seek to produce the same output more efficiently, perhaps with Reduce()
and do.call('rbind', list)
.
I begin with a list of n_iter
elements. Each element contains two elements, each of which contains two additional elements (which contain vectors). That implies four vector "leaves" for each iteration.
As output, I would like to produce a four-element list, with each element containing a matrix of n_iter
rows corresponding to all iterations of one of the four "leaf" vectors (i.e., each row is a "leaf" vector, and a single matrix represents all iterations of that vector).
# Create data
data <- as.data.frame(matrix(rnorm(6000, 0, 1), nrow = 1000, ncol = 6))
names(data) <- c("outcome_1", "outcome_2", "predictor_1a",
"predictor_1b", "predictor_2a", "predictor_2b")
# Specify number of iterations.
n_iter <- 100
# Run bootstrap with 10,000 replicates.
replicates <- replicate(n_iter, {
samp <- data[sample(nrow(data), replace = TRUE), ]
res <- lapply(list(c('predictor_1a', 'predictor_1b'), c('predictor_2a', 'predictor_2b')), function (t) {
lapply(c('outcome_1', 'outcome_2'), function (y) {
form <- as.formula(paste(y, paste(t, collapse = " + "), sep = " ~ "))
res <- lm(form, data = data)$coef
})
})
}, simplify = FALSE)
# Store results for each of the four comparisons in a list object.
repl_version <- list(list(), list(), list(), list())
for (i in 1:n_iter) {
repl_version[[1]][[i]] <- replicates[[i]][[1]][[1]]
repl_version[[2]][[i]] <- replicates[[i]][[1]][[2]]
repl_version[[3]][[i]] <- replicates[[i]][[2]][[1]]
repl_version[[4]][[i]] <- replicates[[i]][[2]][[2]]
}
# Produce SE estimates for each comparison.
repl_version <- lapply(repl_version, function (version) {
version_matrix <- do.call('rbind', version)
})