Skip to content

Simple way to define a function to be used in a formula object inside another function

2 messages · Frank E Harrell Jr, William Dunlap

#
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
#
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