Skip to content

simplify loop

4 messages · Omar Lakkis, Achim Zeileis, Brian Ripley +1 more

#
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
#
On Wed, 11 May 2005 13:05:58 -0400 Omar Lakkis wrote:

            
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
#
It is, backwards, a cumulative product so you could use cumprod.
On Wed, 11 May 2005, Omar Lakkis wrote:

            

  
    
#
Omar Lakkis wrote:
You dont need a loop at all here. How so? Well, as it is written the 
code in the for loop only executes once:

  > settle=1:10
  > for (i in length(settle)-1:1) {
  + print(i)
  + }
  [1] 9
  >

  you have made a mistake, and I think you really want:

  > for (i in (length(settle)-1):1 ) {

  since R does the ':' first and then does 'length(settle)-' unless you 
bracket it:

   > length(settle)-1:1
   [1] 9
   > (length(settle)-1):1
   [1] 9 8 7 6 5 4 3 2 1

I don't see an obvious way to get rid of the for loop though...

Baz