Using 'get' Inside Nested Functions on Local Variables

前端 未结 2 1731
名媛妹妹
名媛妹妹 2021-01-20 00:36

I\'ve never quite gotten my head around nesting functions and passing arguments by reference. My strategy is typically to do something like get(\'variabletopassbyrefer

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-20 01:04

    Also, pass the environment that the variables are located in. Note that parent.frame() refers to the environment in the currently running instance of the caller.

    test1 <- function(a1, b1, env = parent.frame()) {
    
      a <- get(a1, env)
      b <- get(b1, env)
      c <- get('c', env)
    
      testvalue <- c * a * b
    
      testvalue
    
    }
    
    c <- 3
    test2() # test2 as in question
    ## 6
    

    Here a and b are in env c is not in env but it is in an ancestor of env and get looks through ancenstors as well.

    ADDED Note that R formulas can be used to pass variable names with environments:

    test1a <- function(formula) {
        v <- all.vars(formula)
        values <- sapply(v, get, environment(formula))
        prod(values)
    }
    
    test2a <- function() {
        a <- 1
        b <- 2
        test1a(~ a + b + c)
    }
    
    c <- 3
    test2a()
    ## 6
    

    REVISION: Corrected. Added comment. Added info on formulas.

提交回复
热议问题