passing arguments to function expr() in rlang and the !! operator

 ̄綄美尐妖づ 提交于 2020-01-01 19:47:15

问题


Define an expression

> xy <- expr(x+y)

Use it to build a second expression ... and it works

> expr(a + !!xy)

a + (x + y)

simply changing the order of the arguments and it stops working

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

Am I missing something?

Thanks


回答1:


There is way to make it work. Change the way !!xy has been used in expr and it will work. i.e

expr((!!xy) + a)

#(x + y) + a

The reason is that priority of all arithmetic and comparison operators are higher than !. Hence arithmetic and comparison operators binds tightly than !. e.g.:

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

The r-documentation for quasiquotation has clearly mentioned it as:

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


来源:https://stackoverflow.com/questions/49099709/passing-arguments-to-function-expr-in-rlang-and-the-operator

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