[R] What does the "<<-" operator mean?

Rolf Turner rolf.turner at xtra.co.nz
Fri Apr 22 10:35:30 CEST 2011


On 22/04/11 17:53, Liviu Andronic wrote:
> On Thu, Apr 21, 2011 at 9:59 PM, Thomas Lumley<tlumley at uw.edu>  wrote:
>> The Evil and Wrong use is to modify variables in the global environment.
>>
> I'm a bit at a loss. Why is it so wrong and evil?
Because there is extreme danger of accidentally overwriting objects
in your workspace that you ***really*** wanted to keep!
> In other words, how
> should one modify variables in the global environment? Through the use
> of return()?

Roughly speaking yes, though ``return()'' is not strictly necessary.


I.e. the returned value of a function may simply be the value of the
last expression in the function.  E.g.

foo <- function(x) {
     1 + x + x^2
}

and

foo <- function(x) {
     return(1 + x + x^2)
}

are effectively exactly the same function.  Better to say via explicit 
assignment
rather than ``through return()''.

But basically functions should take input and produce output, where
the latter may be assigned to an object the name of which is subject
to your conscious choice.

If you create the function:

bar <- function(x) {
     y <<- 1 + x + x^2
     invisible()
}

and do bar(3) you will wind up with an object named "y" in your workspace
with the value 13.  If you already had an object named "y" in your workspace
(which may have taken hours or days of calculation) it would be gone, 
and you'd
have to repeat those hours or days of calculation.  Also the result of 
bar(x) is
always named "y".

Whereas with the function foo() previously defined you can do

     y <- foo(3)
     x <- foo(4)
     w <- foo(42)

and have all three results available simultaneously to process further.

Moreover you have to *consciously* overwrite an object named "y" by doing
y <- foo(<whatever>).  It can still happen of course, if you're not thinking
carefully, but it's much less likely to happen.

     cheers,

         Rolf Turner



More information about the R-help mailing list