[R] for loop optimization help

Jinsong Zhao jszhao at yeah.net
Mon Aug 27 02:06:34 CEST 2012


Hi there,

In my code, there is a for loop like the following:

    pmatrix <- matrix(NA, nrow = 99, ncol = 10000)
    qmatrix <- matrix(NA, nrow = 99, ncol = 3)
    paf <- seq(0.01, 0.99, 0.01)
    for (i in 1:10000) {
        p.r.1 <- rnorm(1000, 1, 0.5)
        p.r.2 <- rnorm(1000, 2, 1.5)
        p.r.3 <- rnorm(1000, 3, 1)
        pmatrix[,i] <- quantile(c(p.r.1, p.r.2, p.r.3), paf)
    }
    for (i in 1:99) {
       qmatrix[i,] <- quantile(pmatrix[i,], c(0.05, 0.5, 0.95))
    }

Because of the number of loop is very large, e.g., 10000 here, the code 
is very slow.

Is it possible to optimize the code?

Any suggestion will be greatly appreciated.

Regards,
Jinsong



More information about the R-help mailing list