Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

meta-programming and the substitute function in R

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?

like image 742
Big Cat Public Safety Act Avatar asked Nov 20 '25 23:11

Big Cat Public Safety Act


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

like image 134
r2evans Avatar answered Nov 22 '25 18:11

r2evans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!