Skip to content
Prev 325112 / 398503 Next

Speed up or alternative to 'For' loop

How about

for (ir in unique(df$TreeID)) {
  in.ir <- df$TreeID == ir
  df$HeightGrowth[in.ir] <- cumsum(df$Height[in.ir])
}

Seemed fast enough to me.

In R, it is generally good to look for ways to operate on entire vectors
or arrays, rather than element by element within them. The cumsum()
function does that in this example.

-Don