使用tidyeval工具构造列表(如`!!`和`:=`) [英] Constructing lists using tidyeval tools (like `!!` and `:=`)
问题描述
我正在寻找一种基于rlang
软件包中定义的list
构造方法.
I am looking a way for easy list
constructing based on R
's tidyeval framework as defined in the rlang
package.
以下是我要实现的目标:
Below is what I want to achieve:
a <- "item_name"
b <- "item_value"
identical(
list(!!a := !!b), # list(!!a := b) is of course also fine
list(item_name = "item_value")
)
目前我能获得的是:
list(!!a := !!b)
# output
[[1]]
`:=`(!(!a), !(!b)
或者,当添加 quosure 时,它可能会变得更好一点:
Alternatively it can get perhaps a little bit better when adding quosure:
quo(list(!!a := !!b))
# output
<quosure: global>
~list(`:=`("item_name", "item_value"))
不幸的是,我不知道如何从这里继续.
Unfortunately I have no idea how to proceed further from here.
换句话说,我希望具有与dplyr
包中相同的效果:
In other words I would like to have a similar effect like what we can get in the dplyr
package:
transmute(iris, !!a := b)
# first few rows
Sepal.Length Sepal.Width Petal.Length Petal.Width Species item_name
1 5.1 3.5 1.4 0.2 setosa item_value
2 4.9 3.0 1.4 0.2 setosa item_value
3 4.7 3.2 1.3 0.2 setosa item_value
4 4.6 3.1 1.5 0.2 setosa item_value
5 5.0 3.6 1.4 0.2 setosa item_value
6 5.4 3.9 1.7 0.4 setosa item_value
推荐答案
您可以使用rlang::list2()
,该rlang::list2()
支持使用:=
取消名称引用和使用!!!
进行拼接.
You can use rlang::list2()
which supports name-unquoting with :=
and splicing with !!!
.
请注意,由于list2()
不是引号功能,因此您不应该取消引号本身,就像list()
具有更多语法功能一样:
Note that you shouldn't unquote the argument itself since list2()
is not a quoting function, it is just like list()
with a few more syntactic features:
a <- "item_name"
b <- "item_value"
list2(!!a := b)
这篇关于使用tidyeval工具构造列表(如`!!`和`:=`)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!