[R-sig-Geo] R Scoping Rules
Gabor Grothendieck
ggrothendieck at gmail.com
Mon Apr 19 02:59:46 CEST 2010
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:
> simple<-function() {
>
> if(exists("height"))
>
> cat("height exists\n")
>
> else
>
> cat("height does not exist\n")
>
> }
>
>
>
> foo<-function() {
>
> height<-10
>
> simple()
>
> }
>
>
>
>> foo()
>
> height does not exist
>
>
>
> Can somebody please explain why "simple" does not find the "height" variable
> when I run it?
>
>
>
> Is there an easy way to make R use scoping rules like python where it
> searches over all frames to find the value of an symbol?
>
>
>
> Thanks, Steve Eick
>
>
>
>
> [[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at stat.math.ethz.ch
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>
More information about the R-sig-Geo
mailing list