Section 5 Function Environment and Scoping


5.1 Function with one arguent

rm(list = ls())

f <- function(x){
    z <- x^3
    return(z)
}


a <- 2
f(x=a)


5.2 Function: Lazy evaluation

rm(list = ls())

f <- function(x, n){
  z <- x^3
  return(z)
}


a <- 2
f(x=a)


5.3 Function with two mandatory arguments

Error when the function is NOT called with two arguments

rm(list = ls())

f <- function(x, n){
  z <- x^n
  return(z)
}


a <- 2

f(x=a)      # Error

f(x=a, n=5) # Correct

The function is dynamcally called with two arguments. This rule is termed as dynamic scoping of a function.


5.4 Function with free variable(s)

rm(list = ls())

n <- 3

f <- function(x){
  z <- x^n
  return(z)
}

a <- 2
f(x=a)

n <- 3
a <- 5
f(x=a)

n <- 5
a <- 2
f(x=a)

# Error - cannot be called with n as argument
f(x=a, n=3)

Function with free variable:

If the variable is not local to the function, it is looked at its parent environment.

The parent environment is the environment in which the function is defined.

This is called lexical scoping or static scoping. This is a powerful programming paradigm in which a function together with its environment is called function closure.