[R] where/what is i? for loop (black?) magic

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Fri Jun 19 14:54:53 CEST 2009


Duncan Murdoch wrote:
> Liaw, Andy wrote:
>> A colleague and I were trying to understand all the possible things one
>> can do with for loops in R, and found some surprises.  I think we've
>> done sufficient detective work to have a good guess as to what's going
>> on "underneath", but it would be nice to get some confirmation, and
>> better yet, perhaps documentation in the R-lang manual.  Basically, the
>> question is, how/what does R do with the loop index variable?  Below are
>> some examples:
>>   
>
> I think it is documented in the ?Control topic that a copy of the seq 
> argument (the 1:2 in your first example) is made at the beginning, and 
> that
> altering var (your i) doesn't affect the loop.

almost true, in that "copy of the seq" does not necessarily mean a deep 
copy, though, and you *can* affect subsequent iterations by altering 
var, as in this trivialized example:

    e = new.env()
    e$a = 'a'

    seq = list(e, e)
    for (var in seq)
       var[[var$a]] = 'b'
   
    as.list(e)
    # list(a = 'b', b = 'b')


vQ




More information about the R-help mailing list