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

From: Rolf Turner <>
Date: Fri, 22 Apr 2011 20:35:30 +1200

On 22/04/11 17:53, Liviu Andronic wrote:
> On Thu, Apr 21, 2011 at 9:59 PM, Thomas Lumley<> 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


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


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.


         Rolf Turner mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Fri 22 Apr 2011 - 08:37:51 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 22 Apr 2011 - 10:00:32 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive