R - Evaluate a nested function in an environment

前端 未结 2 676
情话喂你
情话喂你 2021-01-05 05:12

I am trying to run a chunk of R code in a sandbox-ed fashion, by loading all the necessary dependencies (functions and data) into a new environment and evaluating an express

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-05 05:40

    Scope is defined when the function is created, not when it's called. See section 10.7 of the Introduction to R manual.

    This seems a bit odd to me, but you get the same behavior even if you avoid assign all together and just use $<-.

    jobenv <- new.env(parent=globalenv())
    jobenv$f1 <- function(x) x*2
    jobenv$f2 <- function(y) f1(y) + 1
    expr <- quote(f2(3))
    eval(expr, envir=jobenv)
    

    This seems to be because the enclosing environment of f1 and f2 is the global environment. I would have expected it to be jobenv.

    > environment(jobenv$f1)
    
    > environment(jobenv$f2)
    
    

    One solution is to explicitly set the environment of each function... but there has to be an easier way.

    > environment(jobenv$f1) <- jobenv
    > environment(jobenv$f2) <- jobenv
    > eval(expr, envir=jobenv)
    [1] 7
    

提交回复
热议问题