Skip to content
Prev 21337 / 63424 Next

attributes of environments

On 7/5/06, Duncan Murdoch <murdoch at stats.uwo.ca> wrote:
Perhaps the example I gave previously does not adequately
convey the problem.  Lets try another example.

#1 uses R as it currently exists.

1. Define an environment e1 with component A.  Now
suppose we wish to define a "subobject" for which
$ is overridden so that it will upper case the
right arg.  We can do this:

e1 <- new.env()
e1$A <- 1

# now define a "subobject" and override $
e2 <- structure(list(env = e1), class = c("myenvironment", "environment"))
"$.myenvironment" <- function(obj, x) obj[["env"]][[toupper(x)]]

e2$a # 1
e2[["A"]]  # NULL since e2 cannot usefully inherit [[

To really get this to work we would have to
redefine all of environment's methods.  I won't do that
here to keep things small.


2. However, if it were possible to have the class
attached to e2 rather than being attached to the environment itself then
e2 could still inherit all the other methods of "environment" yet
be distinct from e1 even though the two would share the same
environment:

# this assumes a attributes are associated with variables
# does not work as intended in R currently since the class(e2)<-
statement also changes e1:

e1 <- new.env()
e1$A <- 1
e2 <- e1
class(e2) <- c("myenvironment", "environment")
"$.myenvironment" <- function(obj, x) obj[[toupper(x)]]
e2$a # 1
e2[["A"]]  # 1

Now all of environment's methods can be used and e1
can still be used in the usual way.

If we typed the above into R now then e1 would be changed
too.  Thus e2 is no longer a "subobject" of e1.  It is e1.
e1$a # 1  -- oops!

Although this example may seem simple I think it represents the essence
of  the situation that exists in a number of packages.  Any package
that currently uses the list(env=...an.environment...) idiom could
likely usefully
make use of this.  Note that in #1 we had to redefine all the methods of
environment to get access to them but if the functionality assumed in
#2 existed then it would inherit them and no further work need be done.