Technicality: entering function definitions in the console causes then to have the enclosing environment set to R_GlobalEnv, so we manually force the enclosures of f and g to match the environment where they "belong":environment(sandbox$f) <- sandboxenvironment(sandbox$g) <- sandbox呼叫g. f找不到本地变量x=123:Calling g. The local variable x=123 is not found by f:> sandbox$g()This is function g. This is function f looking for symbol x: not found. 现在,我们在全局环境中创建一个x并调用g.函数f首先在沙箱中查找x,然后在沙箱的父项中查找,恰好是R_GlobalEnv:Now we create a x in the global environment and call g. The function f will look for x first in sandbox, and then in the parent of sandbox, which happens to be R_GlobalEnv:> x <- 456> sandbox$g()This is function g. This is function f looking for symbol x: 456 只需检查f首先在其外壳中查找x,我们就可以在其中放置x并调用g:Just to check that f looks for x first in its enclosure, we can put a x there and call g:> sandbox$x <- 789> sandbox$g()This is function g. This is function f looking for symbol x: 789 结论:R中的符号查找遵循封闭环境链,而不是执行嵌套函数调用期间创建的评估框架.Conclusion: symbol lookup in R follows the chain of enclosing environments, not the evaluation frames created during execution of nested function calls.只需将链接添加到马丁·摩根(Martin Morgan)关于parent.frame()与parent.env() Just adding a link to this very interesting answer from Martin Morgan on the related subject of parent.frame() vs parent.env() 这篇关于嵌套函数环境选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-22 13:22