Skip to content

Functions within functions - environments

3 messages · Rik Verdonck, Rui Barradas, William Dunlap

#
Hello,

See the help page for parent.frame, and use its argument to go back to 
the frames of variables 'a' and 'b':


innerfunction<-function()
{
     env1 <- parent.frame(1)  # for 'b'
     env2 <- parent.frame(2)  # for 'a'
     print(paste(env2$a, " from inner function"))
     print(paste(env1$b, " from inner function"))
     setwd(wd)
}


Now it complains about 'wd'.
(Are you sure you want to hard code the number of frames to go back to? 
It seems better to write "normal" functions, i.e., functions with 
arguments. innerfunction would have 2 args and middlefunction just one, 
'a'.)

Hope this helps,

Rui Barradas

Em 12-06-2013 18:42, Rik Verdonck escreveu:
#
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