[R] <<- how/when/why do you use it?

Duncan Murdoch murdoch at stats.uwo.ca
Tue Apr 13 16:37:51 CEST 2010


On 13/04/2010 10:02 AM, Tal Galili wrote:
> Hi all,
>
> Today I came across scoping in the R
> intro<http://cran.r-project.org/doc/manuals/R-intro.html#Scope> (after
> reading Robert Gentleman
> fortune<http://rfortunes.posterous.com/im-always-thrilled-when-people-discover-what>
> on
> lexical scooping) , and am very curious about the <<- assignment.
>
> The manual showed one (very interesting) example for "<<-", which I feel I
> understood. What I am still missing is the context of when this can be
> useful.
>
> So what I would love to read from you are examples (or links to examples) on
> when using "<<-" can be interesting/useful. What might be the dangers of
> using it (it looks easy to loose track of), and any tips you might feel like
> sharing.
>   

It's useful in a couple of contexts.

In a big function, sometimes you have repetitive operations on local 
variables:  you can write local functions to do them, and modify the 
outer local variables using <<-.  (See tools::Rd2HTML for lots of 
examples of this.)

There's also the use of them as a way to get references to objects that 
maintain their state, by returning a function from a function:  it can 
refer to and modify local variables in the outer function.  This is used 
in the tkcanvas demo, for example.

One thing to watch out for:  if you have code like this:

x <<- 1 # modifies a non-local ("outer") variable
y <- x  # assignment from outer x

x <- 2  # creates a local

x <<- 3 # modifies the outer one
z <- x  # assignment from local x

then y will get 1, but z will get 2, even though the first and last 
pairs of lines look very similar.  It's generally confusing to mix <<- 
assignments to outer variables with <- assignments to locals having the 
same name.  Just use different names.

Duncan Murdoch



More information about the R-help mailing list