plijnzaad
plijnzaad

Reputation: 329

with(data, expr) construct inside a function renders its parameters invisible?

I'm trying to pass an environment into a function, but can't seem to use it using the ``with'' construct. In the code below:

f <- function(i,env)with(env, i+2*j)

g <- function() {
  env <- new.env()
  env$j <- 3
  f(10, env)
}

g()

I would have expected that inside the ``with'', i would be visible, so g() should return 16. However, I get

Error in eval(expr, envir, enclos) : object 'i' not found

I notice that the docu says that

if ‘data’ is already an environment then this is used with its existing parent,

but that would seem to completely short-circuit all arguments of a function. Wny is this, and why would this be useful behaviour?

(The background to this is that I'm cleaning up old code that had some biggish global variables; I'm trying to stuff that into a big environment that gets passed around, and my hope was that I didn't need to rewrite all read/writes from/to those previously global variables).

Any help appreciated.

Upvotes: 0

Views: 51

Answers (1)

Max Candocia
Max Candocia

Reputation: 4385

i is in the environment of f, but it isn't in the environment of env. You would have to do

f <- function(i,env) with(env,j)*2+i

g <- function() {
  env <- new.env()
  env$j <- 3
  f(10, env)
}

g()

Upvotes: 2

Related Questions