Alex Rivera | Logout

Replicate() versus a for loop?

Asked 2012-11-16T07:37:00.110
8

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.)

Edit
Report

1 Answer

9

replicate is a wrapper for sapply, which itself is a wrapper for lapply. lapply is ultimately an .Internal function that is written in C and performs the looping in an optimised way, rather than through the interpreter. It's main advantages are efficient memory management, especially compared to the highly inefficient vector growing method you present above.

answered 2012-11-16T07:46:59.797

Your Answer