[R] environment question

Jeffrey Horner jeff.horner at vanderbilt.edu
Tue Jul 29 04:42:55 CEST 2008

Edna Bell wrote:
> Hi R users!
> I was looking at some of the example code for the "environment"
> function.  Here it is:
> e1 <- new.env(parent = baseenv())  # this one has enclosure package:base.
> e2 <- new.env(parent = e1)
> assign("a", 3, envir=e1)
> ls(e1)
> ls(e2)
> exists("a", envir=e2)   # this succeeds by inheritance
> exists("a", envir=e2, inherits = FALSE)
> exists("+", envir=e2)   # this succeeds by inheritance
> My question is: how can "a" exist in e2 when the ls(e2) gives
> character(0), please?

It actually doesn't. From the code above here's the inheritance tree for 
the environments:

baseenv() => e1 => e2

When you call exists() on the e2 environment, it actually fails. However 
since the inherits flag is TRUE by default, exists() searches through 
the inherited environments and finds "a" in e1. So, exists will tell you 
that it found "a", just not where it found "a".

However, if you set inherits=FALSE, then exists() searches only in the 
specified environment.



More information about the R-help mailing list