[R] how to modify variables of another frame (but not global)

Thomas Lumley tlumley at u.washington.edu
Tue Mar 23 23:22:29 CET 2004


On Tue, 23 Mar 2004, Thomas Lumley wrote:

> On Tue, 23 Mar 2004, Gabor Grothendieck wrote:
>
> > > The second, f2, uses <<- which searches through its parent environments for the
> > assigned-to variable.  As can be seen in f2a near the end it appears to
> > do the same thing as assign underneath as the entire z in f seems to
> > have been copied over.  Note that the right hand side of the assignment
> > is still handled normally.  QUESTION: Could someone explain what is
> > going on in f2a in detail???
>
<snip>
> Now what appears to happen is that R cleverly optimizes to avoid copying,
> assigning the whole vector z rather than just the first element, since the
> old z will be overwritten anyway. That is, the code to decide whether the
> LHS and RHS are the same vector doesn't seem to be special-cased for <<-.
> I'm not completely sure about this -- the code is complicated.

In fact it's simpler and more wrong than that.  The first z to be found is
the local one, so it gets its first element incremented. So the new value
is  c(11,11,12) and this just gets stuck into the z in the enclosing
environment.

The problem is that the code that decides where to put the result
(eval.c:do_set) starts looking in the enclosing environment, but the code
that computes the result (eval.c:evalseq) starts looking in the local
environment.

That is, the code is equivalent to

*tmp*<-z
*tmp*[1]<-z[1]+1
z<<-*tmp*

where the first two z's are the local one and the last one is in the
enclosing environment.


	-thomas




More information about the R-help mailing list