Using functions and environments

后端 未结 3 2195
星月不相逢
星月不相逢 2020-12-09 13:52

Following the recent discussions here (e.g. 1, 2 ) I am now using environments in some of my code. My question is, how do I create functions that modify environments accordi

3条回答
  •  温柔的废话
    2020-12-09 14:34

    The simplest solution is to use the environment when referencing the object:

    y <- new.env()
    y$x <- 1
    f <- function(env,z) {
        env$x+z
    }
    f(y,z=1)
    

    You would need to assign z to your environment as well.

    y <- new.env()
    with(y, x <- 1)
    f <- function(env,z) {
        assign("z", z, envir=env)
        with(env, x+z)
    }
    f(y,z=1)
    

    One other option would be to attach your environment so that the variables can now be used directly.

    y <- new.env()
    with(y, x <- 1)
    f <- function(env,z) {
        attach(env)
        y <- x + z
        detach(env)
        y
    }
    f(y,z=1)
    

    This latter solution is powerful because it means you can use any object from any attached environment within your new environment, but it also means that you need to be very careful about what has been assigned globally.

    Edit:

    This is interesting, and I don't entirely understand the behavior (i.e. why z is not in the scope of the with call). It has something to do with the creation of the environment originally that is causing it to be outside the scope of the function, because this version works:

    f <- function(z) {
        y <- new.env()
        with(y, x <- 1)
        with(y, x+z)
    }
    f(y,z=1)
    

提交回复
热议问题