[R] Stranger Behavior -maybe not

William Dunlap wdunlap at tibco.com
Sun Oct 4 06:55:56 CEST 2009


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Antonio Paredes
> Sent: Saturday, October 03, 2009 5:53 PM
> To: r-help at r-project.org
> Subject: [R] Stranger Behavior -maybe not
> 
> Hello everyone,
> 
> When I run a for loop I noticed that the looping variable 
> gets assigned the
> last value in the loop:
> 
> For example, if I let h=200, and I run
> 
> for(i in 1:h),
> 
> i gets the value 200. What's wrong here?

That is the way for loops work in R.  After the loop
is done 'i' remains defined to be the last value it had
in the loop, just as any other variable defined in the
loop would remain defined.

In S+ (and S) the 'i' in the loop is defined only within
the loop and disappears after the loop is
done.  If another 'i' were defined before the start of
the loop then it would be masked by the loop's 'i'
until the loop was done and the pre-loop value of 'i'
would then reappear.  I.e., the for loop acted a bit like
a new frame, but unlike the usual frames in S+.  (C++
acts like this, doesn't it, if the 'i' is declared in the for
statement.  R and S don't have declarations so the analogy
isn't good.)

E.g., 
   RS> i<-7
   RS> for(i in 1:3)if(i==2)break
   RS> i
   S+: [1] 7
   R : [1] 2

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> 
> -- 
> -Tony
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 




More information about the R-help mailing list