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)

  1. e2a <- env(d = 4, e = 5)
  2. e2b <- env(e2a, a = 1, b = 2, c = 3)
  3. # e2a is the parent of e2b.

You can find the parent of an environment with env_parent():

  1. env_parent(e2b)
  2. #> <environment: 0x7fe6c7399f58>
  3. env_parent(e2a)
  4. #> <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.

  1. x <- 0
  2. f <- function() {
  3. x <<- 1
  4. }
  5. f()
  6. x
  7. #> [1] 1
  8. 如果使用的是<-
  9. x <- 0
  10. f <- function() {
  11. x <- 1
  12. }
  13. f()
  14. x
  15. #> [1] 0