R - Environment (Scope)


The scoping rules of a language determine how values are assigned to free variables (user variable) Free variables are not:

  • formal arguments
  • local variables (assigned inside the function body).


A function + an environment = a closure or function closure.


Every environment has a parent environment; it is possible for an environment to have multiple “children” the only environment without a parent is the empty environment

Lexical scoping in R means that the values of free variables are searched for in the environment in which the function was defined.

If the value of a symbol is not found in the environment in which a function was defined, then the search is continued in the parent environment.

The search continues down the sequence of parent environments until we hit the top-level environment; this usually the global environment (workspace) or the namespace of a package.

After the top-level environment, the search continues down the search list until we hit the empty environment. If a value for a given symbol cannot be found once the empty environment is arrived at, then an error is thrown.

Powered by ComboStrap