在变量中存储dplyr`filter()`的过滤器

Ale*_*lex 5 r dplyr

我想在同一组条件下过滤多个数据帧.所以我想将这些过滤器设置为filter()调用之外的变量.

例如

mtcars %>%
  filter(cyl > 4, disp > 100)
Run Code Online (Sandbox Code Playgroud)

我试过做:

filters <- c(cyl > 4, disp > 100)
mtcars %>%
  filter(filters)
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为当我设置filters变量时,它会查找dataframe列.

> filters <- c(cyl > 4, disp > 100)
Error: object 'cyl' not found
Run Code Online (Sandbox Code Playgroud)

实现这一目标的最佳方法是什么?

jdo*_*res 7

rlang包允许你创建,然后可以在使用特殊调换不计算表达式!!符号.如果您正在使用dplyr,那么您已经拥有了rlang的关键部分.请注意,对于filter,优秀的做法是明确组合多个条件,而不是依赖于filter多个参数的隐式"和".

my.filter <- quo(cyl > 4 & disp > 100)

filter(mtcars, !!my.filter)

    mpg cyl  disp  hp drat    wt  qsec vs am gear carb
1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
3  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
4  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
5  18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
6  14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
7  19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
8  17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
9  16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3
Run Code Online (Sandbox Code Playgroud)

正如Artem指出的那样,你可以使用带复数quos函数和!!!运算符的逗号表示法:

my.filter <- quos(cyl > 4, disp > 100)

filter(mtcars, !!!my.filter)
Run Code Online (Sandbox Code Playgroud)