Manfredo Manfredo - 2 months ago 21
R Question

Auto assignment

Recently I have been working with a set of R scripts that I inherited from a colleague. It is for me a trusted source but more than once I found in his code auto-assignments like

x <<- x


Is there any scope where such an operation could make sense?

Answer

This is a mechanism for copying a value defined within a function into the global environment (or at least, somewhere within the stack of parent of environments): from ?"<<-"

The operators ‘<<-’ and ‘->>’ are normally only used in functions, and cause a search to be 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.

I don't think it's particularly good practice (R is a mostly-functional language, and it's generally better to avoid function side effects), but it does do something. (@Roland points out in comments and @BrianO'Donnell in his answer [quoting Thomas Lumley] that using <<- is good practice if you're using it to modify a function closure, as in demo(scoping). In my experience it is more often misused to construct global variables than to work cleanly with function closures.)

Consider this example, starting in an empty/clean environment:

f <- function() {
     x <- 1     ## assignment
     x <<- x    ## global assignment
}

Before we call f():

x
## Error: object 'x' not found

Now call f() and try again:

f()
x
## [1] 1
Comments