[R] evaluating variables in the context of a data frame
Prof Brian Ripley
ripley at stats.ox.ac.uk
Fri Jun 8 08:02:07 CEST 2007
On Thu, 7 Jun 2007, Zack Weinberg wrote:
> Given
>
>> D = data.frame(o=gl(2,1,4))
>
> this works as I expected:
>
>> evalq(o, D)
> [1] 1 2 1 2
> Levels: 1 2
>
> but neither of these does:
>
>> 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.
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-help
mailing list