Skip to content
Prev 8063 / 29559 Next

R Scoping Rules

Thanks.  This makes sense.  Is there any way to make R search over every
frame all the way back to the global frame?  

simple <- function(env = parent.frame()) {
   if(exists("height", env)) cat("height exists\n")
   else cat("height does not exist\n")
}
a<-function()simple()
foo <- function() { height <- 3; a() }
foo() # height does not exist

-----Original Message-----
From: Gabor Grothendieck [mailto:ggrothendieck at gmail.com] 
Sent: Sunday, April 18, 2010 8:00 PM
To: eick at cs.uic.edu
Cc: r-sig-geo at stat.math.ethz.ch
Subject: Re: [R-sig-Geo] R Scoping Rules

R uses lexical scope. That means that when a variable is not found in
a function it next looks where the function was _defined_ and not
where the function was called from.   Since simple is defined in the
global environment it looks there for height if can`t find it within
simple.  The parent environment is where the function was defined and
the parent frame is where it was called from.  To force it to look in
the parent frame rather than the parent environment try this:

simple <- function(env = parent.frame()) {
   if(exists("height", env)) cat("height exists\n")
   else cat("height does not exist\n")
}
foo <- function() { height <- 3; simple() }
foo() # height exists
On Sun, Apr 18, 2010 at 8:27 PM, Stephen G. Eick <eick at vistracks.com> wrote:
variable