[R] slow loops in Monte Carlo Simulations

Duncan Murdoch murdoch at stats.uwo.ca
Tue Sep 28 14:58:19 CEST 2004


On Tue, 28 Sep 2004 13:46:04 +0200, "Nael Al Anaswah"
<Nael-Al.Anaswah at WIWI.UNI-MUENSTER.DE> 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?

It'll be a lot faster if you assign your storage at the start:

 - a 100000 long vector to hold the results at the start
 - enough space to hold a full iteration at the start

Extending vectors is slow, because it requires a new allocation and a
copy operation.

The Writing R Extensions manual talks about linking C, C++ or Fortran
code into R.  It'll likely be faster, but if you need to allocated R
storage from within it, there's a bit of a learning curve.

Duncan Murdoch




More information about the R-help mailing list