Skip to content
Back to formatted view

Raw Message

Message-ID: <97di201lmt4olugcajuejn1jmi8ifm8cc0@4ax.com>
Date: 2004-02-10T19:56:01Z
From: Duncan Murdoch
Subject: Constructing an environment from a data.frame

Code like

df <- data.frame(x=1:10)
y <- 20:29

eval(quote(x+y), env=df)

does what you might expect:  it looks for x and y in the data.frame,
and when it doesn't find y there, it looks in the parent environment.

However, sometimes I'd like to construct a single environment out of
df, so that I can pass it to nested functions and get the same
behaviour.  Right now, I get the wrong answer from code like this:

f1 <- function(df) {
    g <- function() {
	eval(quote(x+y), env=df)
    }
    y <- 1:10
    g()
}

f1(df)

because the eval looks in the environment of f1, finds y there, and
gives me the wrong answer.

I can modify f1 so it works:

f2 <- function(df) {
    g <- function(env) {
	eval(quote(x+y), env=df, enclos=env)
    }
    y <- 1:10
    g(parent.frame())
}

but this means carrying around both parent.frame() and df.  I'd like
to do this:

f3 <- function(df) {
    env <- as.environment(df)

    g <- function() {
	eval(quote(x+y), env=env)
    }

    y <- 1:10
    g()
}

and get the same result as from f2(df), but currently as.environment
doesn't like to be passed a data.frame.  Is there a better way to do
the same thing?

Duncan Murdoch