[R] evaluating variables in the context of a data frame
Duncan Murdoch
murdoch at stats.uwo.ca
Fri Jun 8 20:38:49 CEST 2007
On 6/8/2007 11:33 AM, Zack Weinberg wrote:
> On 6/7/07, Prof Brian Ripley <ripley at 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
More information about the R-help
mailing list