I have seen a couple related questions on this topic, for instance here and here but the solutions don't seem to work for me as far as I can tell.
I have a function that returns a 5x3 matrix. I use mapply to iterate the function 4 times. My goal is to have the mapply call return a 20x3 matrix, but instead it returns a 15x4 matrix.
population <- runif(100, 0, 1)
iterations <- seq(1:4)
test.func <- function(k){
samp1 <- sample(population, 20, replace = FALSE)
samp2 <- sample(population, 20, replace = FALSE)
samp3 <- sample(population, 20, replace = FALSE)
## Pre-allocate
c1 <- NULL
c2 <- NULL
c3 <- NULL
for (i in 1:5){
c1[i] <- samp1[i]
c2[i] <- samp2[i]
c3[i] <- samp3[i]
}
combined <- cbind(c1, c2, c3)
print(combined)
}
results <- mapply(FUN = test.func, k = iterations)
I tried a transpose within the function, but that didn't help. I'd be open to options that fix the problem after calling mapply too.
One alternative would be to convert the 5x3 matrices to data frames and then separate them into a 3x20 matrix and transpose it. But I am hoping there is a more sensible way.