[R] Is it possible to vectorize/accelerate this?

Carl Witthoft carl at witthoft.com
Thu Nov 3 23:29:22 CET 2011


I have to admit to not doing careful timing tests, but I often eliminate 
if() lines as follows (bad/good is just my preference)

BAD:  b[i] <- if(a[i]>1) a[i] else a[i-1]

GOOD:  b[i] <- a[i]* (a[i]>1) + a[i-1] * (a[i]<=1)




On Thu, Nov 3, 2011 at 12:10 PM, hihi <v.p.mail_at_freemail.hu> wrote:
 > Dear Members,
 >
 > I work on a simulaton experiment but it has an bottleneck. It's quite 
fast because of R and vectorizing, but it has a very slow for loop. The 
adjacent element of a vector (in terms of index number) depends 
conditionally on the former value of itself. Like a simple cumulating 
function (eg. cumsum) but with condition. Let's show me an example:
 > a_vec = rnorm(100)
 > b_vec = rep(0, 100)
 > b_vec[1]=a_vec[1]
 > for (i in 2:100){b_vec[i]=ifelse(abs(b_vec[i-1]+a_vec[i])>1, 
a_vec[i], b_vec[i-1]+a_vec[i])}
 > print(b_vec)
-- 

Sent from my Cray XK6
"Pendeo-navem mei anguillae plena est."



More information about the R-help mailing list