Frank Harrell
2013-Dec-15 18:08 UTC
[R] Simple way to define a function to be used in a formula object inside another function
I would like to do this:
f <- function(formula, data=NULL) {
gg <- sqrt
model.frame(formula, data=data)
}
x <- y <- 1:10
f(y ~ gg(x))
Error in eval(expr, envir, enclos) : could not find function "gg"
Is there a simple way to get access to gg from within the model.frame
invocation inside f?
Thanks
Frank
William Dunlap
2013-Dec-15 18:46 UTC
[R] Simple way to define a function to be used in a formula object inside another function
The following works because model.frame looks for things in environment(formula)
and ancestral environments thereof. It puts the new things in a child
environment
of the original environment(formula) so it does not alter the original
environment.
f2 <- function (formula, data = NULL)
{
environment(formula) <- new.env(parent = environment(formula))
assign(envir = environment(formula), "gg", sqrt)
model.frame(formula, data = data)
}
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at
r-project.org] On Behalf
> Of Frank Harrell
> Sent: Sunday, December 15, 2013 10:09 AM
> To: RHELP
> Subject: [R] Simple way to define a function to be used in a formula object
inside another
> function
>
> I would like to do this:
>
> f <- function(formula, data=NULL) {
> gg <- sqrt
> model.frame(formula, data=data)
> }
> x <- y <- 1:10
> f(y ~ gg(x))
> Error in eval(expr, envir, enclos) : could not find function "gg"
>
> Is there a simple way to get access to gg from within the model.frame
> invocation inside f?
>
> Thanks
> Frank
>
> ______________________________________________
> R-help at r-project.org 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.