Skip to content
Prev 325260 / 398503 Next

Functions within functions - environments

A function looks up free variables in the environment in which the function
was defined, not in the environment in which the function was called.  The
latter is called something like 'dynamic scoping' and usually leads to trouble,
the former is 'lexical scoping' and leads to predictable results.  You can do
dynamic scoping in R (using get(), assign(), and parent.frame()), but it
leads to code that only works correctly in favorable circumstances.  You should pass
data from the caller to the callee via the argument list, not via free variables.

To use lexical scoping define your functions as:

outerfunction<-function()
{
     middlefunction<-function()
     {
          innerfunction<-function()
          {
              print(paste(a, " from inner function"))
              print(paste(b, " from inner function"))
              # setwd(wd) # wd was not defined in your mail
        }
        b="b"
        print(paste(b, " from middle function"))
        innerfunction()
     }
     a="a"
     print(paste(a," from outer function"))
     middlefunction()
}
[1] "a  from outer function"
[1] "b  from middle function"
[1] "a  from inner function"
[1] "b  from inner function"

(One can change the environment of a function after it is defined, but
there is not often a need to do that.)

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com