R函数将未经评估的参数传递给其他函数 [英] R functions that pass on unevaluated arguments to other functions

查看:78
本文介绍了R函数将未经评估的参数传递给其他函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在尝试理解R中的惰性评估.这使我感到困惑:

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"

为什么gh的行为方式不同?

Why do g and h not behave the same way?

推荐答案

R的惰性评估方面是,它直到需要使用时才评估对象.但是,您所看到的与惰性评估无关.而是与省略号参数有关:

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:

调用g(y)时,f用省略号替换x的值.但是substitute(...)本质上替代了发送给省略号的值(在这种情况下,省略号的作用与另一个替代调用类似[em] [不完全]).

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

在调用h(y)时,f再次替换了x的值,该值是除椭圆以外的值,即z,因此替换了该值.

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.

请查看以下内容,然后在您的环境中执行.

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)

这篇关于R函数将未经评估的参数传递给其他函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆