[R] slow loops in Monte Carlo Simulations

Gardar Johannesson johannesson1 at llnl.gov
Tue Sep 28 17:18:01 CEST 2004


The key is to assign space in advance -- e.g., compare:

 > N <- 20000
 >
 > res <- NULL
 > system.time( for(i in 1:N) res <- c(res, sample(10)) )
[1] 28.62  8.91 37.79  0.00  0.00
 >
 > res <- vector("list",N)
 > system.time( for(i in 1:N) res[[i]] <- sample(10) )
[1] 0.45 0.00 0.44 0.00 0.00
 >
 > res <- matrix(0.0, N,10)
 > system.time( for(i in 1:N) res[i,] <- sample(10) )
[1] 0.47 0.01 0.47 0.00 0.00
 >


Gardar

At 01:46 PM 9/28/2004 +0200, Nael Al Anaswah wrote:
>Hi there,
>
>I am running Monte Carlo Simulations in R using ordinary "while
>(condition)" loops. Since the number of iterations is something like
>100.000 and within each iteration a given subsample is extended
>sequentially it takes hours to run the simulation.
>
>Does anyone know if there is either a way to avoid using loops in
>Monte Carlo Simulations or how to include possible faster "c++"
>commands in R code?
>
>many thanks in advance.
>
>Nael Al-Anaswah
>
>
>
>-----------------------------------------------------
>Nael Al-Anaswah
>Department of Econometrics
>University of Muenster
>Germany
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html




More information about the R-help mailing list