5

What are the differences in the assignment operators <- and <<- in R?

And when should <<- be used?

Thomas
  • 43,637
  • 12
  • 109
  • 140
csiu
  • 3,159
  • 2
  • 24
  • 26
  • this was asked before: http://stackoverflow.com/questions/5785290/what-is-the-difference-between-assign-and-in-r – joekz Feb 21 '14 at 20:54
  • 1
    See also [this](http://stackoverflow.com/q/9851655/324364) and [this](http://stackoverflow.com/questions/10904124/global-and-local-variables-in-r). The latter in particular is a very close duplicate. – joran Feb 21 '14 at 20:57
  • 3
    I'd simply forget about `<<-`, I've never seen a valid use for it. Global variables are not needed, and for ugly, hard to read and maintain code. – Paul Hiemstra Feb 21 '14 at 20:58
  • 1
    @PaulHiemstra, you don't consider closures a valid use? I'm thinking particularly of the case where `<<-` doesn't assign to the global environment, but rather, to an intermediate enclosing environment. – BrodieG Feb 21 '14 at 21:45
  • 1
    @BrodieG Saying there is *no* place for `<<-` is probably not true (although I have not used `<<-` in my several years of R programming). But in the vast majority of situations it is not necessary. In addition, the cases where it is applicable are probably quite complex situations (you mention nested environments), while `<<-` is more abused by novice programmers in simple situations. – Paul Hiemstra Feb 22 '14 at 07:36
  • @PaulHiemstra, yes you are right. – BrodieG Feb 22 '14 at 12:42
  • @BrodieG you mentioned in the vast majority of situations `<<-` is not necessary. What would you have done instead in my proposed answer (found below) for the usage of `<<-`? – csiu Feb 24 '14 at 07:43
  • @csiu, see **[this discussion](http://stackoverflow.com/questions/10659133/local-variables-within-aes/10659410#10659410)** in another SO question – BrodieG Feb 24 '14 at 13:17

1 Answers1

7

<- assigns an object to the environment in which it is evaluated (local scope). <<- assigns an object to the next highest environment that the name is found in or the global namespace if no name is found. See the documentation here.

<<- is usually only used in functions, but be careful. <<- can be much harder to debug because it is harder to trace the evaluation of the assignment. It is better to write functions with return statements instead.

Hadley Wickham has a good explination in his Advanced R Programming Book.

Christopher Louden
  • 7,540
  • 2
  • 26
  • 29