I have a question about global assignment. Here is a small example. I would like to ask why the second global assignment do not affect inside the function?And why the return output of function is different from what I call for outside the function after I run the function)
Thanks!
Here's my explanation, it's very complicated but I've tried my best:
a_function
in the first line you assigned X to the matrix of 3 in the global environmentX
, added every element by 4 and then assigned it to X
in the global environment (with <<-
), overriding the previous value of X
in the global environment. But more interestingly (and difficult to see / untuit from the code), is what happens to X
in the function environment. Due to lazy evaluation, now is when R finds a value for X
within the function environment - it evaluates the promise, which is to evaluate the expression X
in the enclosing environment of the function. We just bound the matrix of 3's to X
in the global environment. So now the value of X
in the function environment is also the matrix of 3s.a_function(X)
it returns the matrix of 3s.X
is evaluated in the global environment, it returns the matrix of 7s (because you globally assigned it there from within your function using <<-
).