basic question
- Environment vs list
- parent of the global environment?
- enclosing environment of a function
- determine the environment from which a function was called
- <- and <<- different?
Environment bisics
important environment
Access the global environment with globalenv() and the current environment with environment()
parent environment
Every environment has a parent
The parent is what’s used to implement lexical scoping: if a name is not found in an environment, then R will look in its parent (and so on)
e2a <- env(d = 4, e = 5)e2b <- env(e2a, a = 1, b = 2, c = 3)# e2a is the parent of e2b.
You can find the parent of an environment with env_parent():
env_parent(e2b)#> <environment: 0x7fe6c7399f58>env_parent(e2a)#> <environment: R_GlobalEnv>
Super assignment, <<-
Super assignment, <<-, never creates a variable in the current environment, but instead modifies an existing variable found in a parent environment.
x <- 0f <- function() {x <<- 1}f()x#> [1] 1如果使用的是<-x <- 0f <- function() {x <- 1}f()x#> [1] 0
