I'm still trying to understand lazy evaluation in R. Here's something that confuses me:
f=function(x) as.character(substitute(x))
g=function(...) f(...)
h=function(z) f(z)
f(y)
# [1] "y"
g(y)
# [1] "y"
h(y)
# [1] "z"
Why do g
and h
not behave the same way?
The Lazy Evaluation aspect of R
is that it does not evaluate an object until it is needed. However, what you are seeing has little to do with lazy evaluation. Rather it is related to the ellipsis argument:
When calling g(y)
, f
is substituting the value of x with the ellipsis. But substitute(...)
essentially substitutes in the value sent to the ellipsis (in this context, the ellipsis act similar [not exactly] to another call to substitute).
When calling h(y)
, again f
is substituting the value of x
, which is a value other than ellipses, namely z
and so substitutes in that value.
Edit as per @Alexander's comment:
Please have a look at the following and execute in your environment.
f=function(x) {cat("\nHERE IS THE OUTPUT FOR `f`: "); as.character(substitute(x))}
g=function(...) {cat("I am evaluating the first argument", ..1, "\n"); f(...)}
h=function(z) {print(z); f(z)}
y <- "Look, I am evaluated!\n"
f(y)
g(y)
h(y)
来源:https://stackoverflow.com/questions/18049248/r-functions-that-pass-on-unevaluated-arguments-to-other-functions