Home > Net >  r-How the global assignment affect inside the function?(Especially there are 2 global assignments)
r-How the global assignment affect inside the function?(Especially there are 2 global assignments)

Time:11-20

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!

enter image description here enter image description here

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 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.
  • 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 <<-).
  • Related