From wdunlap at tibco.com  Thu May 13 20:55:01 2010
From: wdunlap at tibco.com (William Dunlap)
Date: Thu, 13 May 2010 11:55:01 -0700
Subject: [Rd] What functions are called internally in R to resolve
	whatvariable is referred?
In-Reply-To: <AANLkTimZ57TV_geRPsAGB9CEBq6iv2V91EmFPMU1awQ0@mail.gmail.com>
References: <AANLkTimZ57TV_geRPsAGB9CEBq6iv2V91EmFPMU1awQ0@mail.gmail.com>
Message-ID: <77EB52C6DD32BA4D87471DCD70C8D70002F1E307@NA-PA-VBE03.na.tibco.com>


> From: r-devel-bounces at r-project.org 
> [mailto:r-devel-bounces at r-project.org] On Behalf Of 
> thmsfuller066 at gmail.com
> Sent: Thursday, May 13, 2010 10:16 AM
> To: r-devel at r-project.org
> Subject: [Rd] What functions are called internally in R to 
> resolve whatvariable is referred?
> 
> Hello All,
> 
> If I refer to a variable 'x', 'x' will be searched in the current
> frame or the parent frame, or the parent of the parent frame, etc.,
> until it is found (or not found at all)?

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 

> Could you please show me what
> code in R source that handles this? Is it in the C code or the R code?
>
> Thanks,
> Tom



[Rd] What functions are called internally in R to resolve whatvariable is referred?
William Dunlap