R environments and function call stacks

独自空忆成欢 提交于 2020-01-14 07:58:07

问题


I am trying to use get in series of function calls, but the lookup of the object names seems to skip environments. For example:

foo <- 1 # variable in .GlobalEnv

getter <- function(x) {get(x)}
getter("foo") # returns 1, which is expected

f1 <- function() {
  foo <- 2 # local variable in the function scope
  getter("foo")
}

f1() # still returns 1, would've expected to return 2

Why is it that calling f1 returns the foo in the global environment and not the foo in the calling function's environment?

How do I have get look in the calling function's environment? Setting pos = sys.parent() does not seem to work.


回答1:


If you define getter to look in the parent frame, it works:

getter <- function(x) get(x, envir=parent.frame())

Then:

getter("foo")
[1] 1

f1()
[1] 2



回答2:


You are being tripped up by the subtle differences between frames and environments (which is even more subtle since frames are environments, or maybe environments are frames) and the difference between lexical and dynamic scoping. There are some details in the help page for parent.frame and other places spread across various documentation.

To try and simplify:

Your getter function has its own environment where variables local to that function are stored (x in this case). Since R is lexically scoped that means that the functions environment has a parent environment which is defined by where the function is defined, the global environment in this case (if it were defined inside of another function then the parent environment would be the env for that function).

When you call f1 and it calls getter then getter tries to find the variable foo, it first looks in its own environment, does not find it there, then looks in its parent environment which is the global env and finds foo with the value of 1.

Your thinking goes along the lines of dynamic scoping, which the frames approximate. When f1 is called it gets its own environment (within which foo will be assigned the value 2), then it calls the getter function. The environment of foo is not the parent of getter's env (lexical scoping), but the environment of f1 is the parent frame of getter since getter was called from f1, so to look in the environment of f1 you need to tell the get function to look in the parent frame rather than the parent environment.

The summary of this is that the parent environment is the environment where a function was defined (lexical scoping), the parent frame is the frame/environment from which the function was called (simulated dynamic scoping).



来源:https://stackoverflow.com/questions/12492226/r-environments-and-function-call-stacks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!