将参数传递给rlang中的函数expr()和!!操作者

问题描述 投票:1回答:1

Define an expression

> xy <- expr(x+y)

用它来构建第二个表达式......它可以工作

> expr(a + !!xy)

a + (x + y)

只需更改参数的顺序,它就会停止工作

> expr(!!xy + a)
Error in (function (x)  : object 'a' not found

我错过了什么吗?

谢谢

r rlang
1个回答
1
投票

有办法让它发挥作用。改变!!xyexpr中使用的方式,它将起作用。即

expr((!!xy) + a)

#(x + y) + a

原因是所有算术和比较运算符的优先级都高于!。因此算术和比较运算符比!紧密绑定。例如。:

> expr(!!2 + 3)
[1] 5
> expr((!!2) + 3)
(2) + 3

quasiquotation的r文档明确提到它:

# 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)
© www.soinside.com 2019 - 2024. All rights reserved.