-1

Possible Duplicate:
How do you use “<<-” (scoping assignment) in R?

I am reading a pseudocode. I came across with this <<- many times. What is the significance of <<-? What does it mean? And what do we need to consider or be careful with when using the <<- operator?

Community
  • 1
  • 1
user1769197
  • 2,132
  • 5
  • 18
  • 32
  • Related: [Why is using `<<-` frowned upon and how can I avoid it?](http://stackoverflow.com/q/9851655/271616) – Joshua Ulrich Nov 07 '12 at 15:53
  • 5
    -1 Was there something wrong with the documentation you looked at prior to asking the question? You are expected to show some effort of having tried to help yourself. [so] isn't meant to replace reading the documentation for whatever tool you are using. – Gavin Simpson Nov 07 '12 at 15:54

1 Answers1

12

From the help file ?"<<-":

The operators <<- and ->> are normally only used in functions, and cause a search to made through parent environments for an existing definition of the variable being assigned. If such a variable is found (and its binding is not locked) then its value is redefined, otherwise assignment takes place in the global environment. Note that their semantics differ from that in the S language, but are useful in conjunction with the scoping rules of R. See ‘The R Language Definition’ manual for further details and examples.

Here is an example:

foo <- function(){
  a <<- 1
}

Now run it and see how it creates a new object a in the global environment:

a
Error: object 'a' not found

foo()
a
[1] 1

The reason that one should try to avoid this, is that it breaks the functional programming paradigm. In functional programming, one writes functions that depend only on their inputs and produce no side effects.

The side effect of <<- is to create a new object in the parent environment, and is therefore no longer functional programming.

In most day-to-day use it isn't necessary to use <<-, although it can be useful when using closures that have state, i.e. remember what they did in the past. This is described in wonderful detail in Hadley's devtools wiki

Andrie
  • 176,377
  • 47
  • 447
  • 496