Search code examples
rattributesformulaenvironment

Return formula in parent environment


If I have an R function that returns a formula, it is bound to the function's scope/environment. What can I do from within the function so that the returned formula does not have this environment attribute?

E.g.,

myfun = function() {
    model = y ~ 1
    return(model)
}

Result:

> myfun()
# y ~ 1
# <environment: 0x000001ffd94eca50>

One solution is modifying the attribute before return:

myfun = function() {
    model = y ~ 1
    attr(model, ".Environment") = globalenv()
    return(model)
}

But this looks hacky, so is it really the best way?


Solution

  • I might use the parent environment rather than the global enviroment

    myfun <- function() {
        model <- y ~ 1
        environment(model) <- parent.frame()
        return(model)
    }
    

    That will create the environment from where you call it, bit globalenv() would also be fine if you prefer always the global environment.