6.5 More about functions insights

6.5.1 Lexical scoping

Rules

  • Name masking
  • Functions versus variables
  • A fresh start
  • Dynamic lookup

Debugging

This function

g12 <- function() x + 1
x <- 15
g12()
#> [1] 16
codetools::findGlobals(g12)
#> [1] "+" "x"

You can change the function’s environment to an environment which contains nothing:

# environment(g12) <- emptyenv()
# g12()
# Error in x + 1 : could not find function "+"

6.5.2 … (dot-dot-dot)

Example

i01 <- function(y, z) {
  list(y = y, z = z)
}
i02 <- function(x, ...) {
  i01(...)
}
str(i02(x = 1, y = 2, z = 3))
#> List of 2
#>  $ y: num 2
#>  $ z: num 3
#> List of 2
#>  $ y: num 2
#>  $ z: num 3

6.5.3 Exiting a function

  1. Implicit or explicit returns

  2. Invisibility (<- most famous function that returns an invisible value)

  3. stop() to stop a function with an error.

  4. Exit handlers

6.5.4 Function forms

Everything that exists is an object. Everything that happens is a function call. — John Chambers