Re: [R] evaluating variables in the context of a data frame

From: Duncan Murdoch <>
Date: Fri, 08 Jun 2007 14:38:49 -0400

On 6/8/2007 11:33 AM, Zack Weinberg wrote:
> On 6/7/07, Prof Brian Ripley <> wrote:

>> >> f <- function(x, dat) evalq(x, dat)
>> >> f(o, D)
>> > Error in eval(expr, envir, enclos) : object "o" not found
>> >> g <- function(x, dat) eval(x, dat)
>> >> g(o, D)
>> > Error in eval(x, dat) : object "o" not found
>> >
>> > What am I doing wrong?  This seems to be what the helpfiles say you do
>> > to evaluate arguments in the context of a passed-in data frame...
>> When you call f(o, D), the argument 'o' is evaluated in the current
>> environment ('context' in R means something different).  Because of lazy
>> evaluation, it is not evaluated until evalq is called, but it evaluated as
>> if it was evaluated greedily.
>> g(quote(o), D) will work.

> Thanks.
> After a bit more experimentation I figured out that this does what I want:
>> h <- function(x, d) eval(substitute(x), d, parent.frame())

> but I don't understand why the substitute() helps, or indeed why it
> has any effect at all...

Within the evaluation frame of h, x is a promise to evaluate an expression. substitute(x) extracts the expression. If you just use x, it gets evaluated in the frame from which h was called, rather than in a frame created from d.

Duncan Murdoch mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Fri 08 Jun 2007 - 18:43:49 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 08 Jun 2007 - 19:31:34 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.