I am trying to understand the behavior of substitute here, here are my examples, If you run both the examples, f1 and f2 gives you "b" and "k" as answers. The only difference in both the codes is that, I have added list(y = 'z')
which doesn't contain any x. I was under the assumption that this should not change the behavior of substitute however it did. Can anyone possibly tell me what is happening here? Thank you very much in advance
x <- 'a'
a <- 'b'
f1 <- function(x){
s = substitute(x, list(y = 'z'))
print(s) ## this returns x !!! why?
a <- 'k'
print(eval(s))
}
f1(a) ## returns "b"
f2 <- function(x){
s = substitute(x)
print(s) ## this returns a which is fine.
a <- 'k'
print(eval(s))
}
f2(a) ## returns "k"
This is because the two parameters that substitute
takes are
substitute(expr, env)
expr - any syntactically valid R expression
env - an environment or a list object. Defaults to the current evaluation environment.
So the when you call substitute(x)
, that's the same as substitute(x, environment())
. substitute
works by pull the value of the promise from the local function environment to get the symbol used to call the function. If you use substitute(x, list(y = 'z'))
, it no longer will use the local environment so it can't see the x
value that was passed as parameter.