People often use the attach()
and detach()
functions to set up "search paths" for variable names in R, but because this alters global state that's hard to keep track of, people recommend using with()
instead, which sets up a temporary alteration to the search path for the duration of a single expression.
However I just noticed that unlike attach()
, with()
apparently doesn't "resolve through" functions. For example, let's first set up a dummy function that will access a variable named x
:
f <- function { print(x) }
Now,
with(list(x=42), f())
fails even though
with(list(x=42), print(x))
and
attach(list(x=42))
f()
both succeed! :(
Can anyone tell me why? I would like with()
to behave exactly like attach()
does here, to enable me to effectively pass a big parameter list to a function by setting up an environment containing the parameter values with with()
. I see this approach as having several benefits over the alternatives (the two I've considered are (a) laboriously passing all the parameters into the function, and (b) explicitly passing in a list/frame of parameters as a function argument and having the function itself call with()
), but it doesn't work. I find this discrepancy pretty troubling to be honest! Any explanation/help would be appreciated.
I'm using R 2.11.1.