0

it takes about an hour to this loop. Is there any way make this faster?

l <- 2

while (l < 300001) {
  VV[1,l] = log(b+(l-1) * 0.001-0.0005) + k + 
    beta * (1-delta) * (1-p * sum(Pr[1,(1:l)])) * V[1, l] + 
    beta  *(1-delta) * p * sum((V[1,] * Pr[1,])[(l+1):300001])
  l = l + 1
}
amatsuo_net
  • 2,409
  • 11
  • 20
  • 5
    Hi and welcome to SO. Please read https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example and rephrase your question accordingly. – Julian_Hn Apr 17 '19 at 07:52
  • Have a look at https://adv-r.hadley.nz/perf-improve.html – Phil Apr 17 '19 at 08:07
  • It seems that the calculation can be done without a loop. You should try doing it as a vector/matrix calculation. Or provide some sample data so that others can try. – amatsuo_net Apr 17 '19 at 09:44

1 Answers1

1

If on *nix (Linux, Unix, macOS, ...) you can use parallel processing:

library(parallel)

VV <- matrix(ncol = 300001)
mclapply(2:300001, function(l){
  VV[1,l] <<- log(b+(l-1) * 0.001-0.0005) + k + beta * (1-delta) * (1-p * sum(Pr[1,(1:l)])) * V[1,l]+beta  *(1-delta) * p * sum((V[1,] * Pr[1,])[(l+1):300001])
  }, mc.cores = 5)
Simon
  • 577
  • 3
  • 9