We have
=
<-
<<-
Can someone explain exactly what they do? If there are any more? When I use <<-, it seems to mess my functions but, but I want to declare things globally so I have them when the function is done (I don't want to return them from the function because I'm optimizing over something else)
Answer
In some sense =
and <-
are equivalent, but the latter is preferred because =
is also overwritten to specify default arguments (where <-
will not work).
As for <<-
, it is trickier and not recommended. In R, every step of execution along arbitrary code will be associated with a stack of environments--the current environment, the environment the current function was called from, etc. The operator <<-
attempts to assign a value to the nearest object found in this environment hierarchy, and if none is found, assign it within the global environment. For example, below is a rudimentary adder.
f <- (function() { x <- 0; function(y) { x <<- x + y; x } })()
f(10) # 10
f(5) # 15
The function f
has an environment which has a parent environment which has x
. Using <<-
, we can access that x
, whereas if we had <-
, the result would have been y
every time instead of keeping track of the sum. The reason for this is that <-
would have created a copy of x
in the local scope, and it would always be 0
since the value was copied from the parent environment.
For further information about these intricacies, you can also look at the relevant R documentation.
No comments:
Post a Comment