[R] how to eval subset?
Prof Brian Ripley
ripley at stats.ox.ac.uk
Sat Feb 10 08:32:13 CET 2007
You mean the 'subset' argument to model.frame and not subset() the
function, I think.
The answer is on the help page for model.frame[.default].
All the variables in 'formula', 'subset' and in '...' are looked
for first in 'data' and then in the environment of 'formula' (see
the help for 'formula()' for further details) and collected into a
data frame.
The evaluation frame of f2 (where you defined 'subs') is not a place that
is searched. There are various workarounds, and in your case calling
model.frame() in f2 to assemble 'data' would work. (Had you
transformations had in your formula it would not, but R-devel has
get_all_vars() for this purpose.)
On Sat, 10 Feb 2007, Ott-Siim Toomet wrote:
> Hi,
>
> I have problems with subset when calling a function from inside a function
> from inside a function. Here is a small example to be called as 'f1()'.
> 'eval()' in f3 fails with error message
>
> Error in eval(expr, envir, enclos) : object "subs" not found
>
> Is it possible to supplement subset to data, to be calculated in a
> different environment than the data itself?
>
> Thanks in advance
> Ott
>
> The example follows:
> ----------------------------------------------------------
> N <- 10
> f1 <- function() {
> x <- runif(N)
> y <- runif(N)
> f2(y ~ x)
> }
>
> f2 <- function(formula, data=sys.frame(sys.parent())) {
> subs <- rep(c(TRUE, FALSE), length.out=N)
> f3(formula, data=data, subset=subs)
> }
>
> f3 <- function(formula, data=sys.frame(sys.parent()), subset) {
> mf <- match.call()
> m <- match(c("formula", "subset", "data"), names(mf), 0)
> mf <- mf[c(1, m)]
> mf[[1]] <- as.name("model.frame")
> eval(data)
> # anyone able to explain me why this eval is necessary?
> # can it be done in a smarter way?
> mf <- eval(mf, envir=parent.frame())
> # finds the data environment, but not environment for subset
> }
>
> ______________________________________________
> 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.
>
--
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