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