在 dplyr 的过滤器中同时使用空过滤器和字符串过滤器

Tim*_* S. 6 r dplyr nse

我正在使用不推荐dplyr::filter_()使用的dplyr::filter(). 但我不能让它再用于空过滤器字符串:

例子:

library(dplyr)
my_df <- tibble::tibble(x = sample(c(0:9), 100, replace = TRUE))
Run Code Online (Sandbox Code Playgroud)

不推荐使用filter_()字符串和空字符串

fil1 <- "x == 5"
filter_(mydf, .dots = fil1) # works

fil2 <- NULL
filter_(mydf, .dots = fil2) # works, returns all values
Run Code Online (Sandbox Code Playgroud)

NSE 版本仅适用于带引号的过滤器值,但不适用于空值

fil1 = quo(x == 5)
filter(my_df, !!enquo(fil1)) # works

fil2 = NULL
filter(my_df, !!enquo(fil2)) 
Error: Argument 2 filter condition does not evaluate to a logical vector

fil2 = quo(NULL)
filter(my_df, !!enquo(fil2))
Error: Argument 2 filter condition does not evaluate to a logical vector
Run Code Online (Sandbox Code Playgroud)

我看到了三种可能的方法:

  • 报价NULL不同
  • 使用另一个表达式代替 NULL
  • 在里面使用另一个参数 filter()

Chu*_*k P 2

如果我正确理解你@timm-s,第二个项目符号选项意味着我可以提供这个解决方案。

\n\n
set.seed(2020)\nlibrary(dplyr)\n\nmy_df <- tibble::tibble(x = sample(c(0:9), 100, replace = TRUE))\n\nfil1 <- quo(x == 5)\nfilter(my_df, !!enquo(fil1)) # works\n#> # A tibble: 11 x 1\n#>        x\n#>    <int>\n#>  1     5\n#>  2     5\n#>  3     5\n#>  4     5\n#>  5     5\n#>  6     5\n#>  7     5\n#>  8     5\n#>  9     5\n#> 10     5\n#> 11     5\n\nfil2 <- TRUE\nfilter(my_df, !!enquo(fil2)) \n#> # A tibble: 100 x 1\n#>        x\n#>    <int>\n#>  1     6\n#>  2     5\n#>  3     7\n#>  4     0\n#>  5     0\n#>  6     3\n#>  7     9\n#>  8     5\n#>  9     0\n#> 10     7\n#> # \xe2\x80\xa6 with 90 more rows\n
Run Code Online (Sandbox Code Playgroud)\n\n

它只是依赖于真/假的事实filter,所以不要告诉它什么都告诉它是真的。对我来说,真正的问题是为什么filter_认为 NULL 是真的,哈哈。

\n\n

多玩一点就会发现可以对空盒子进行更多简化

\n\n
fil3 <- TRUE\nfilter(my_df, fil3) \n
Run Code Online (Sandbox Code Playgroud)\n\n

也可以,但可能不适合您的情况。

\n