且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么是 enquo + !!优于替代 + 评估

更新时间:2023-11-29 16:18:40

我想给出一个独立于 dplyr 的答案,因为使用 enquo 超过 substitute.两者都查看函数的调用环境以识别赋予该函数的表达式.不同之处在于 substitute() 只执行一次,而 !!enquo() 会正确地遍历整个调用堆栈.

I want to give an answer that is independent of dplyr, because there is a very clear advantage to using enquo over substitute. Both look in the calling environment of a function to identify the expression that was given to that function. The difference is that substitute() does it only once, while !!enquo() will correctly walk up the entire calling stack.

考虑一个使用 substitute() 的简单函数:

Consider a simple function that uses substitute():

f <- function( myExpr ) {
  eval( substitute(myExpr), list(a=2, b=3) )
}

f(a+b)   # 5
f(a*b)   # 6

当调用嵌套在另一个函数中时,此功能会中断:

This functionality breaks when the call is nested inside another function:

g <- function( myExpr ) {
  val <- f( substitute(myExpr) )
  ## Do some stuff
  val
}

g(a+b)
# myExpr     <-- OOPS

现在考虑使用 enquo() 重写的相同函数:

Now consider the same functions re-written using enquo():

library( rlang )

f2 <- function( myExpr ) {
  eval_tidy( enquo(myExpr), list(a=2, b=3) )
}

g2 <- function( myExpr ) {
  val <- f2( !!enquo(myExpr) )
  val
}

g2( a+b )    # 5
g2( b/a )    # 1.5

这就是为什么 enquo() + !! 优于 substitute() + eval()>.dplyr 只是充分利用了这个特性来构建一组连贯的 NSE 函数.

And that is why enquo() + !! is preferable to substitute() + eval(). dplyr simply takes full advantage of this property to build a coherent set of NSE functions.

更新: rlang 0.4.0 引入了一个新的运算符 {{(发音为curly curly"),它实际上是一个简写对于 !!enquo().这允许我们将 g2 的定义简化为

UPDATE: rlang 0.4.0 introduced a new operator {{ (pronounced "curly curly"), which is effectively a short hand for !!enquo(). This allows us to simplify the definition of g2 to

g2 <- function( myExpr ) {
  val <- f2( {{myExpr}} )
  val
}