0

I am trying to evaluate an R function in a specific environment and getting different results than expected.

Example below, I would like to eval my function in testEnv, but when I set envir to that it still uses the global variable. I am not sure why it does that, ChatGPT also suggests this method.

testEnv<-env(x = 1000)

testEnv$x

func1 <- function(){
  2 + x
}

x <- 1

func1()


eval(func1(), envir = testEnv)

This returns 3 instead of 1003.

jpsmith
  • 11,023
  • 5
  • 15
  • 36
kemoT
  • 1
  • 2
  • 2
    See the `with_env` function in the duplicate. There's a discussion there of what's going on. But basically the function stores the environment where it's defined and uses that to loop up free varibales; it does not use the function where it was called. Using `eval(envir=)` only changes the calling environment which doesn't make a difference for free variables. Instead you can do `environment(func1) <- testEnv; func1()` – MrFlick Aug 29 '23 at 17:19

0 Answers0