If you look at the beginning of lm(), you'll see that match.call() is used and name of the function (in this case "f1") is replaced with "model.frame". Does something like this work?

f1 <- function(formula, data) {
        mf <- match.call(expand.dots = FALSE)
        mf[[1]] <- as.name("model.frame")
        eval(mf, parent.frame())
}

-roger

Heather Turner wrote:
I'm trying to evaluate a pre-built expression using eval(), e.g.

dataset <- data.frame(y = runif(30, 50,100), x = gl(5, 6))

# one like this
mf <- expression(model.frame(y~x))
eval(mf, dataset, parent.frame())

# rather than this
eval(expression(model.frame(y~x)), dataset, parent.frame())

In the example above there is no problem, the problem comes when I try to do a 
similar thing within a function, e.g.

f1 <- function(formula, data) {
    mt <- terms(formula)
    mf <- as.expression(as.call(c(as.name("model.frame"), formula = mt)))
    eval(mf, data, parent.frame())
}


f1(formula = y ~ x, data = dataset)

Error in eval(expr, envir, enclos) : Object "y" not found

I can get round this by building a call to eval using paste, e.g.

f2 <- function(formula, data) {
    mt <- terms(formula)
    mf <- as.expression(as.call(c(as.name("model.frame"), formula = mt)))
    direct <- parse(text = paste("eval(expression(", mf,
               "), data, parent.frame())"))
    print(direct)
    eval(direct)
}


f2(formula = y ~ x, data = dataset)

expression(eval(expression(model.frame(formula = y ~ x)), data, parent.frame()))
y x
1 92.23087 1
2 63.43658 1
3 55.24448 1
4 72.75650 1
5 67.58781 1
...


but this seems rather convoluted. Can anyone explain why f1 doesn't work (when 
f2 does) and/or suggest a neater way of dealing with this?

Thanks

Heather

Mrs H Turner
Research Assistant
Dept. of Statistics
University of Warwick

______________________________________________
R-help@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


-- Roger D. Peng http://www.biostat.jhsph.edu/~rpeng/

______________________________________________
R-help@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

Reply via email to