[R] “For” calculation is so slow

Zhou Fang zhou.zfang at gmail.com
Tue May 22 11:53:08 CEST 2012


For loops are really, really slow in R. In general, you want to avoid them
like the plague. If you absolutely must insist on using them in large,
computationally intense and complex code, consider implementing the relevant
parts in C, say, and calling that from R.

Staying within R, you can probably considerably speed up that code by
storing gx and gy as a multi-dimensional arrays. (e.g. for sample data,
something like

rawGy = sample( 1:240, 240^2* 241, replace = T)
rawGx = sample( 1:240, 240^2 *241, replace = T)
gx = array(rawGx, dim = c(length(s) - 1, 240,  max(rawGx)+1  ) )
gy = array(rawGy, dim = c(length(s) - 1, 240,  max(rawGy)+1 ) )

 ), in which case, you can easily do the computation without loops by

gxa = (gx[ ,a,1]+ 1)
gya =(gy[ ,a, 1] +1)
uv = gx[cbind(1:(length(s) - 1) , b, gxa)] / gx[cbind(1:(length(s) - 1) , a,
gxa)]  - gy[cbind(1:(length(s) - 1) ,b, gya)]/gy[cbind(1:(length(s) - 1) ,a,
gya)]

or similar, which will be enormously faster (on my computer, there's an over
30x speed up). With a bit of thought, I'm sure you can also figure out how
to let it vectorise in a, as well...

Zhou

--
View this message in context: http://r.789695.n4.nabble.com/For-calculation-is-so-slow-tp4630830p4630855.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list