[R-sig-hpc] Avoiding looping on vector with stochastic dependency

Guillaume Chapron carnivorescience at gmail.com
Sun Dec 28 16:03:08 CET 2008


Hello,

I need to perform a computation on a vector, where the value at index  
i is a stochastic function of the value at index i-1. A example would  
the following code:


w <- numeric(100)
w[1] <- 10

# set.seed(2)

for (i in 2:length(w)) {
		w[i] <- sum(rbinom(w[i-1],1,0.5)) + sum(rpois(w[i-1],0.5))
	}


In my program, this code would be executed many times, and I would  
like to have it running faster. I assume I could do this be removing  
the loop and using a vector operation. But, whatever the way I think,  
I cannot figure out how to remove the loop on the index. I would be  
grateful if you could tell me if this is possible?

Thanks so much!!

Guillaume



More information about the R-sig-hpc mailing list