I just finished reading about scoping in the R intro, and am very curious about the <<- assignment.
The manual showed one (very interesting) example for <<-, which I feel I understood. What I am still missing is the context of when this can be useful.
So what I would love to read from you are examples (or links to examples) on when the use of <<- can be interesting/useful. What might be the dangers of using it (it looks easy to loose track of), and any tips you might feel like sharing.
<<-is most useful in conjunction with closures to maintain state. Here’s a section from a recent paper of mine:The ability to manage variables at two levels also makes it possible to maintain the state across function invocations by allowing a function to modify variables in the environment of its parent. The key to managing variables at different levels is the double arrow assignment operator
<<-. Unlike the usual single arrow assignment (<-) that always works on the current level, the double arrow operator can modify variables in parent levels.This makes it possible to maintain a counter that records how many times a function has been called, as the following example shows. Each time
new_counteris run, it creates an environment, initialises the counteriin this environment, and then creates a new function.The new function is a closure, and its environment is the enclosing environment. When the closures
counter_oneandcounter_twoare run, each one modifies the counter in its enclosing environment and then returns the current count.