Skip to content
Prev 257702 / 398502 Next

What does the "<<-" operator mean?

On 22/04/11 17:53, Liviu Andronic wrote:
Because there is extreme danger of accidentally overwriting objects
in your workspace that you ***really*** wanted to keep!
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