Suppose I want perform a simulation using the following function:
fn1 <- function(N) {
res <- c()
for (i in 1:N) {
x <- rnorm(2)
res <- c(res, x[2]-x[1])
}
res
}
For very large N, computation appears to hang. Are there better ways of doing this?
(Inspired by: https://stat.ethz.ch/pipermail/r-help/2008-February/155591.html)
For loops in R are notoriously slow, but here there’s another issue. It’s much faster to preallocate the results vector, res, rather append to res at each iteration.
Below we can compare the speed of the above version with a version that simply starts with a vector, res, of length N and changes the ith element during the loop.
Also, as Sharpie points out, we can make this slightly faster by using R functions like
apply(or its relatives,sapplyandlapply).