R - Evaluate a nested function in an environment

前端 未结 2 530
情话喂你
情话喂你 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:48

    There are a number of ways of doing this, but I kind of like this one:

    jobenv <- new.env(parent=globalenv())
    
    local({
        f1 <- function(x) x*2
        f2 <- function(y) f1(y) + 1
    }, envir=jobenv)
    
    ## Check that it works
    ls(jobenv)
    # [1] "f1" "f2"
    local(f2(3), envir=jobenv)
    # [1] 7
    eval(quote(f2(3)), envir=jobenv)
    # [1] 7
    

提交回复
热议问题