Re: [R] simplify loop

From: Achim Zeileis <Achim.Zeileis_at_wu-wien.ac.at>
Date: Thu 12 May 2005 - 03:21:13 EST

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[n]:

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.
Z

> ______________________________________________
> R-help@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
>

R-help@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 Received on Thu May 12 03:34:41 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:31:41 EST