Question:
What does the <<-
operator in R mean, what are its differences from <-
and under what circumstances might it be useful?
Answer:
I'll explain with an example.
> objeto_fora_da_funcao <- 1
> f <- function() {
objeto_fora_da_funcao <- 10
return(objeto_fora_da_funcao)
}
Outputs
> f()
# [1] 10
> objeto_fora_da_funcao
# [1] 1
Now, let's change <-
to <<-
inside the f
function:
> objeto_fora_da_funcao <- 1
> f <- function() {
objeto_fora_da_funcao <<- 10
return(objeto_fora_da_funcao)
}
Notice the outputs now:
Outputs
> objeto_fora_da_funcao
# [1] 1
> f()
# [1] 10
> objeto_fora_da_funcao
# [1] 10
What's behind this is the way R stores objects in "environments", which could be seen as sets of objects (numbers, vectors, data.frames, functions, etc.).
<<-
is generally useful within functions, as functions work with their own temporary "environments". Although functions access global objects, the <-
operator is programmed to create (or redefine) objects within the "environment" of the respective function, only. And that's exactly why the <<-
exists. It will look for objects with that given name in all "environments" from the most specific to the most comprehensive (known as "Global environment").
This is useful when you want a function to change global variables.