R functions that pass on unevaluated arguments to other functions

北战南征 提交于 2019-12-10 09:43:45

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!