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

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Thu Jan 29 18:15:29 CET 2009


Duncan Murdoch wrote:
> On 1/29/2009 10:39 AM, davidr at rhotrading.com wrote:

<snip>

>
>> And if the loop variable does not exist before the 'for', why is it
>> created in the parent(?) environment at all?
>
> 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.

... and it's by no means idiosyncratic to r; many dynamic languages do
it this way.

>
>> (I.e, if ii did not exist before the for loop, it does and has value 5
>> after. Wouldn't strict
>> scoping mean that ii exists only within the for loop?)
>
> 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.
>
>> I generally don't try to change the loop variable's value inside a loop,
>> but coming from C
>> or other languages, it seems natural to do so in certain circumstances.
>
> 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.

in the iso c99 standard the following is illegal:

for (int i = 0; i < 10; i++) ...

and you have to declare the iterator variable in advance:

int i;
for (i = 0; i < 10; i++) ...

which effectively works as the r code above, so no surprises if you're
coming from c99 c.  it is different in c++:

int i = 0;
for (int i = 0; i < 10; i++) ...
// i still 0 here

(and this won't go in c99, again).

vQ




More information about the R-help mailing list