Does anyone know how the replicate() function works in R and how efficient it is relative to using a for loop?
For example, is there any efficiency difference between…
means <- replicate(100000, mean(rnorm(50)))
And…
means <- c()
for(i in 1:100000) {
means <- c(means, mean(rnorm(50)))
}
(I may have typed something slightly off above, but you get the idea.)
You can just benchmark the code and get your answer empirically. Note that I also added a second for loop flavor which circumvents the growing vector problem by preallocating the vector.
Looking at the
relativecolumn, the un-preallocated for loop is 6.2 times slower. However, the preallocated for loop is just as fast asreplicate.