meta-programming and the substitute function in R

Viewed 55
f <- function() {
  x <- 6 + 4
  substitute(x)
}
f()

The above will output:

[1] 10

However, the below:

x <- 6 + 4
substitute(x)

outputs:

x

Why are they different?

2 Answers

@akrun's answer demonstrates how to get it to resolve, but I think the answer to your question of "Why?" is in ?substitute, where it says in the Details:

If it is an ordinary variable, its value is substituted, unless env is .GlobalEnv in which case the symbol is left unchanged.

(Emphasis mine.) When you are executing this on the default prompt >, you are in the global environment. Not so in your first example, within the function's namespace. (As to "Why did R-core decide on this behavior?", I do not think I am qualified to answer or even speculate.)

The evaluation is not happening

eval(substitute(x))
#[1] 10

As @r2evans showed the documentation description, we can test it on a new environment to see this in action

# create the object in another environment
e1 <- new.env()
e1$x <- 6 + 4
substitute(x) # here x is looked in the global space
#x
substitute(x, env = e1) # specify the `env` and looks for the local env
#[1] 10
Related