3
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 Answers2

4

@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.)

r2evans
  • 141,215
  • 6
  • 77
  • 149
  • One reason I like questions like this on SO is that ... I didn't know this before hand, and would never have guessed that this would be the default behavior. It seems odd, but then again a couple of decades of sometimes-spiral development with backwards compatibility requirements leads to slightly inconsistent behaviors. It was likely the best choice at the time (and perhaps still is for reasons I don't understand \*shrug\*). – r2evans Jun 25 '19 at 15:58
  • `substitute(X, list(X = x))` is a common usage which will work here – moodymudskipper Jun 25 '19 at 17:16
1

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
akrun
  • 874,273
  • 37
  • 540
  • 662