[R] Question about <<- assignment

Hsiu-Khuern Tang hsiu-khuern.tang at hp.com
Thu Jul 2 04:30:03 CEST 2009


Rolf Turner <r.turner <at> auckland.ac.nz> writes:

> 
> 
> On 2/07/2009, at 12:20 PM, Hsiu-Khuern Tang wrote:
> 
> > Is this expected behavior?
> >
> >> z <- 1:5
> >> z[1] <<- 0
> > Error in z[1] <<- 0 : object "z" not found
> >
> > The documentation seems to suggest that z will be found in the global
> > environment and modified accordingly.
> 
> But I doubt that R Core will move
> to build a "[<<-" operator, even should it prove to be possible.

Thanks for your reply.  Upon more careful reading of the manuals, I think the
behavior I observed _is_ documented.  The "<<-" form of assignment looks for the
target variable in the enclosing environment.  I had mistakenly thought that it
looks for the target variable in the current or enclosing environment.

This is made clear in
http://cran.r-project.org/doc/manuals/R-lang.html#Subset-assignment:

== snip ==
     e<-c(a=1,b=2)
     i<-1
     local({
        e <- c(A=10,B=11)
        i <-2
        e[i] <<- e[i]+1
     })

uses the local value of i on both the LHS and RHS, and the local value of e on
the RHS of the superassignment statement. It sets e in the outer environment to
      a  b
      1 12
== snip ==

As whether using <<- is good practice, I think there are valid and natural uses.
 There are some examples in the R manuals, for example,
http://cran.r-project.org/doc/manuals/R-intro.html#Scope

Best,
Hsiu-Khuern.




More information about the R-help mailing list