11.5 环境
环境是复杂的,建议阅读原文.
The last component of a function is its environment. This is not something you need to understand deeply when you first start writing functions. However, it’s important to know a little bit about environments because they are crucial to how functions work. The environment of a function controls how R finds the value associated with a name. For example, take this function:
<- function(x) {
f + y
x }
在很多其他的编程语言中这样定义函数是错误的,因为没有定义y
.在R中,这是有效的代码,因为R使用称为lexical scoping
的方式寻找关联值.在函数内部没有定义y
,将在上一层环境中查看y
:
<- 100
y f(10)
#> [1] 110
<- 1000
y f(10)
#> [1] 1010
具体详细的资料请查阅: