Duncan Murdoch wrote: > On 1/29/2009 10:39 AM, dav...@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 ______________________________________________ R-help@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.