Re: [R] simplify loop

From: Barry Rowlingson <B.Rowlingson_at_lancaster.ac.uk>
Date: Thu 12 May 2005 - 03:34:30 EST

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



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:41:28 2005

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