Skip to content
Prev 168588 / 398502 Next

scoping rules for 'for' [was - Re: for/if loop ]

On 1/29/2009 10:39 AM, davidr at rhotrading.com wrote:
I don't see that it does.  First time through, it prints 1, 20, 21, 21. 
  Second time through (without ii==1 being true), it prints 2, 2, 3, 3.
Third time through it prints 3,3,4,4.  What's different?
It's created in the current evaluation frame, because that's where 
everything gets created unless you work hard to have it created 
somewhere else.
R doesn't have scoping as strict as that.  For loops don't create their 
own evaluation frames.  If they did, you could not do something like this:

  x <- 0
  for (i in 1:10) {
   x <- x + i
  }

as a slow way to do sum(1:10), because the assignment within the loop 
would take place in a local evaluation frame, and be lost afterwards.
R is not C.  Feel free to do what you like to the variable within the 
loop (though you might cause Luke to grind his teeth when it messes up 
his compiler).  It will be set to the next value in the 1:10 vector the 
next time it comes back to the top.
No, the scoping rules in R are quite simple and consistent.  for and 
while have the same rules.

Duncan Murdoch