Skip to content
Prev 36704 / 63424 Next

What functions are called internally in R to resolve whatvariable is referred?

Be careful with your terms here.  While a function
is evaluating its 'parent frame' is the environment
of the function that called it and its 'parent environment'
is the environment in which it was defined.  R searches
though the chain of parent environments, not parent frames.

The following example shows the difference between the
parent environment and the parent frame.

  # setup
  x <- "Global x"
  f1 <- function() {
      c(x=x,
        xFromParentFrame=get("x", envir=parent.frame()),
        xFromParentEnv=get("x", envir=parent.env(environment())))
  }

  f0 <- function(i) {
     x<-paste("f0's x: i=", i, sep="")
     # Note how subf0 and f1 have identical definitions:
     # they only differ in where they were created.
     subf0 <- function ()
     {
        c(x = x,
          xFromParentFrame = get("x", envir = parent.frame()),
          xFromParentEnv = get("x", envir = parent.env(environment())))
     }
     list(subf0=subf0(), f1=f1(), FUN=subf0)
  }

  > # run the functions
  > z <- f0(17)
  > z
  $subf0
                 x xFromParentFrame   xFromParentEnv
    "f0's x: i=17"   "f0's x: i=17"   "f0's x: i=17"

  $f1
                 x xFromParentFrame   xFromParentEnv
        "Global x"   "f0's x: i=17"       "Global x"

  $FUN
  function ()
  {
      c(x = x, xFromParentFrame = get("x", envir = parent.frame()),
          xFromParentEnv = get("x", envir = parent.env(environment())))
  }
  <environment: 0x292af70>

  > z$FUN()
                 x xFromParentFrame   xFromParentEnv
    "f0's x: i=17"       "Global x"   "f0's x: i=17"

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com