Skip to content
Prev 276308 / 398506 Next

Is it possible to vectorize/accelerate this?

Hi:

You're doing the right thing in R by pre-allocating memory for the
result, but ifelse() is a vectorized function and your loop is
operating elementwise, so if-else is more appropriate. Try

for (i in 2:100){
    b_vec[i] <- if(abs(b_vec[i-1] + a_vec[i]) > 1) a_vec[i] else
b_vec[i-1] + a_vec[i]
  }

If speed is an issue, then I echo Michael's suggestion to write a
C(++) function and call it within R. The inline package is good for
this kind of thing.

HTH,
Dennis
On Thu, Nov 3, 2011 at 12:10 PM, hihi <v.p.mail at freemail.hu> wrote: