将参数传递给 rlang 中的函数 expr() 和 !!操作员
passing arguments to function expr() in rlang and the !! operator
定义一个表达式
> xy <- expr(x+y)
用它来构建第二个表达式...而且有效
> expr(a + !!xy)
a + (x + y)
只需更改参数的顺序,它就会停止工作
> expr(!!xy + a)
Error in (function (x) : object 'a' not found
我是不是漏掉了什么?
谢谢
有办法让它发挥作用。改变 !!xy
在 expr
中的使用方式,它将起作用。即
expr((!!xy) + a)
#(x + y) + a
原因是所有算术运算符和比较运算符的优先级都高于!
。因此,算术运算符和比较运算符比 !
绑定得更紧密。例如:
> expr(!!2 + 3)
[1] 5
> expr((!!2) + 3)
(2) + 3
quasiquotation
的 r-documentation 已明确提及:
# The !! operator is a handy syntactic shortcut for unquoting with
# UQ(). However you need to be a bit careful with operator
# precedence. All arithmetic and comparison operators bind more
# tightly than `!`:
quo(1 + !! (1 + 2 + 3) + 10)
# For this reason you should always wrap the unquoted expression
# with parentheses when operators are involved:
quo(1 + (!! 1 + 2 + 3) + 10)
# Or you can use the explicit unquote function:
quo(1 + UQ(1 + 2 + 3) + 10)
定义一个表达式
> xy <- expr(x+y)
用它来构建第二个表达式...而且有效
> expr(a + !!xy)
a + (x + y)
只需更改参数的顺序,它就会停止工作
> expr(!!xy + a)
Error in (function (x) : object 'a' not found
我是不是漏掉了什么?
谢谢
有办法让它发挥作用。改变 !!xy
在 expr
中的使用方式,它将起作用。即
expr((!!xy) + a)
#(x + y) + a
原因是所有算术运算符和比较运算符的优先级都高于!
。因此,算术运算符和比较运算符比 !
绑定得更紧密。例如:
> expr(!!2 + 3)
[1] 5
> expr((!!2) + 3)
(2) + 3
quasiquotation
的 r-documentation 已明确提及:
# The !! operator is a handy syntactic shortcut for unquoting with # UQ(). However you need to be a bit careful with operator # precedence. All arithmetic and comparison operators bind more # tightly than `!`: quo(1 + !! (1 + 2 + 3) + 10) # For this reason you should always wrap the unquoted expression # with parentheses when operators are involved: quo(1 + (!! 1 + 2 + 3) + 10) # Or you can use the explicit unquote function: quo(1 + UQ(1 + 2 + 3) + 10)