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

From: Duncan Murdoch <murdoch_at_stats.uwo.ca>
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 <ripley@stats.ox.ac.uk> 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



R-help_at_stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html 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 https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.