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:

f <- function(x) {
  x + y
} 

在很多其他的编程语言中这样定义函数是错误的,因为没有定义y.在R中,这是有效的代码,因为R使用称为lexical scoping的方式寻找关联值.在函数内部没有定义y,将在上一层环境中查看y:

y <- 100
f(10)
#> [1] 110

y <- 1000
f(10)
#> [1] 1010

具体详细的资料请查阅:

https://r4ds.had.co.nz/functions.html#environment

http://adv-r.had.co.nz/