在dplyr动词中将字符串作为参数传递 [英] Passing strings as arguments in dplyr verbs
问题描述
我希望能够为 dplyr
动词定义自变量
I would like to be able to define arguments for dplyr
verbs
condition <- "dist > 50"
,然后在<$ c中使用这些字符串$ c> dplyr 函数:
require(ggplot2)
ds <- cars
ds1 <- ds %>%
filter (eval(condition))
ds1
但是它会引发错误
Error: filter condition does not evaluate to a logical vector.
代码应评估为:
ds1<- ds %>%
filter(dist > 50)
ds1
结果是:
ds1
ds1
speed dist
1 14 60
2 14 80
3 15 54
4 18 56
5 18 76
6 18 84
7 19 68
8 20 52
9 20 56
10 20 64
11 22 66
12 23 54
13 24 70
14 24 92
15 24 93
16 24 120
17 25 85
问题:
如何在<$ c中将字符串作为参数传递$ c> dplyr 动词?
推荐答案
自2014年以来,使用< a href = https://rlang.r-lib.org/reference/quasiquotation.html rel = noreferrer> rlang的准报价。
Since these 2014 answers, two new ways are possible using rlang's quasiquotation.
方便为了便于比较,该语句 dist> 50
直接包含在 dplyr :: filter()
中。
library(magrittr)
# The filter statement is hard-coded inside the function.
cars_subset_0 <- function( ) {
cars %>%
dplyr::filter(dist > 50)
}
cars_subset_0()
结果:
speed dist
1 14 60
2 14 80
3 15 54
4 18 56
...
17 25 85
使用NSE的郎朗方法(非标准评估)。如使用dplyr 小插图进行编程,语句 dist> 50
由 rlang :: enquo处理()
,它使用某种黑魔法来查看参数,查看用户键入的内容,然后将该值返回给定值。然后rlang的 !!
取消对输入的引用,以便在周围环境中立即对其进行评估。
rlang approach with NSE (nonstandard evaluation). As described in the Programming with dplyr vignette, the statement dist > 50
is processed by rlang::enquo()
, which "uses some dark magic to look at the argument, see what the user typed, and return that value as a quosure". Then rlang's !!
unquotes the input "so that it’s evaluated immediately in the surrounding context".
# The filter statement is evaluated with NSE.
cars_subset_1 <- function( filter_statement ) {
filter_statement_en <- rlang::enquo(filter_statement)
message("filter statement: `", filter_statement_en, "`.")
cars %>%
dplyr::filter(!!filter_statement_en)
}
cars_subset_1(dist > 50)
结果:
filter statement: `~dist > 50`.
<quosure>
expr: ^dist > 50
env: global
speed dist
1 14 60
2 14 80
3 15 54
4 18 56
17 25 85
rlang方法传递字符串。语句 dist> 50
作为显式字符串传递给函数,并由 rlang :: parse_expr()
,然后用 !!
取消引用。
rlang approach passing a string. The statement "dist > 50"
is passed to the function as an explicit string, and parsed as an expression by rlang::parse_expr()
, then unquoted by !!
.
# The filter statement is passed a string.
cars_subset_2 <- function( filter_statement ) {
filter_statement_expr <- rlang::parse_expr(filter_statement)
message("filter statement: `", filter_statement_expr, "`.")
cars %>%
dplyr::filter(!!filter_statement_expr)
}
cars_subset_2("dist > 50")
结果:
filter statement: `>dist50`.
speed dist
1 14 60
2 14 80
3 15 54
4 18 56
...
17 25 85
使用 dplyr :: select()
,事情变得更简单。显式字符串只需要 !!
。
Things are simpler with dplyr::select()
. Explicit strings need only !!
.
# The select statement is passed a string.
cars_subset_2b <- function( select_statement ) {
cars %>%
dplyr::select(!!select_statement)
}
cars_subset_2b("dist")
这篇关于在dplyr动词中将字符串作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!