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_functionin 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 toXin the global environment (with<<-), overriding the previous value ofXin the global environment. But more interestingly (and difficult to see / untuit from the code), is what happens toXin the function environment. Due to lazy evaluation, now is when R finds a value forXwithin the function environment - it evaluates the promise, which is to evaluate the expressionXin the enclosing environment of the function. We just bound the matrix of 3's toXin the global environment. So now the value ofXin 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
Xis evaluated in the global environment, it returns the matrix of 7s (because you globally assigned it there from within your function using<<-).


