[R] simplify loop

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Wed May 11 19:34:30 CEST 2005


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])
>         }

  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




More information about the R-help mailing list