pass objects to nested functions using environments

137 views Asked by At

I want to pass objects from one function to another nested function assigning environments. Below is a sample of my code which does not work. How this can happen by assigning environments in the function?

sumi <- function(x,y) {
    my.env <- new.env()

    my.env$rumi <- function() {
        my.env$k <- x[1]
        my.env$f <- y[1]
    }
    k <- get("k", my.env)
    f <- get("f", my.env)
    z <- k+f
    return(z)
}
1

There are 1 answers

0
G. Grothendieck On

The code defines but then never runs rumi so the objects it would have created if run never are.

Adding the line marked ### it works:

sumi <- function(x,y) {
    my.env <- new.env()

    my.env$rumi <- function() {
        my.env$k <- x[1]
        my.env$f <- y[1]
    }
    my.env$rumi()  ###
    k <- get("k", my.env)
    f <- get("f", my.env)
    z <- k+f
    return(z)
}
sumi(1, 2)
## [1] 3