[R] How to speed up a for() loop
Phil Spector
spector at stat.berkeley.edu
Thu Feb 17 18:59:54 CET 2011
Simona -
I don't think preallocating your random variables would make
the code run any faster.
A very simple change that would speed things up a little would
be to replace
simPD.vec[i]=length(R.vec[R.vec<cutoff.])
with
simPD.vec[i] = sum(R.vec < cutoff.)
Since you're using a different set of random numbers for each
element of systemic, I don't see an easy way to vectorize your
code (which doesn't mean that such a way doesn't exist).
- Phil Spector
Statistical Computing Facility
Department of Statistics
UC Berkeley
spector at stat.berkeley.edu
On Thu, 17 Feb 2011, simona.costanzo at ubs.com wrote:
>
> Dear all,
>
> Does anyone have any idea on how to speed up the for() loop below.
> Currently it takes approximately 2 minutes and 30 seconds.
>
> Because of the size of Nsim and N, simulating a multivariate normal
> (instead of simulating Nsim times a vector of N normal distributions)
> would require too much memory space.
>
> Many thanks for your kind help,
>
> Simona
>
>
> N=3000
> PD=runif(N,0,1)
> cutoff.=qnorm(PD)
>
> rho.=0.1
>
> Nsim=100000
> simPD.vec=0*(1:Nsim)
>
> systemic = rnorm(Nsim,0,1);
>
> for (i in 1:Nsim)
> {
> R.vec=sqrt(rho.)*systemic[i]+sqrt(1-rho.)*rnorm(N,0,1)
> simPD.vec[i]=length(R.vec[R.vec<cutoff.])
> }
>
>
>
>
More information about the R-help
mailing list