[R] simplify loop

Achim Zeileis Achim.Zeileis at wu-wien.ac.at
Wed May 11 19:21:13 CEST 2005

On Wed, 11 May 2005 13:05:58 -0400 Omar Lakkis wrote:

> Is there a way to implement this faster than doing it in a loop. 
>         for (i in length(settle)-1:1) {
>                 settle[i] = settle[i+1]/(1 + settle.pct[i+1])
>         }
> I want to guarantee that i+1 is calculated before i

Yes, as the loop above as only one iteration, you can easily do it as:
  n <- length(settle)
  settle[n-1] <- settle[n]/(1 + settle.pct[n])

What you probably really meant, can also be simply done without a for
loop. You need a vector settle.pct and a scalar starting value (not a
full vector) settle. So in the following settle is assumed to be only

  settle/c(rev(cumprod(1 + rev(settle.pct)))[-1], 1)

If settle.pct should in fact also be only be constant, this can of
course be further simplified.

> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html

More information about the R-help mailing list