passing arguments to function expr() in rlang and

2019-04-15 03:35发布

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

标签: r rlang
1条回答
Explosion°爆炸
2楼-- · 2019-04-15 04:10

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)
查看更多
登录 后发表回答