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!
CodePudding user response:
Here's my explanation, it's very complicated but I've tried my best:
- in
a_function
in the first line you assigned X to the matrix of 3 in the global environment - in line two you took
X
, added every element by 4 and then assigned it toX
in the global environment (with<<-
), overriding the previous value ofX
in the global environment. But more interestingly (and difficult to see / untuit from the code), is what happens toX
in the function environment. Due to lazy evaluation, now is when R finds a value forX
within the function environment - it evaluates the promise, which is to evaluate the expressionX
in the enclosing environment of the function. We just bound the matrix of 3's toX
in the global environment. So now the value ofX
in the function environment is also the matrix of 3s. - This explains why when you call
a_function(X)
it returns the matrix of 3s. - Then when the expression
X
is evaluated in the global environment, it returns the matrix of 7s (because you globally assigned it there from within your function using<<-
).