What is the tidyeval way of using dplyr::filter?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 09:09:54

You are most of the way there except for a minor typo, the round brackets in your filter statement should be on the variable and not the value.

print(df %>% filter((!!x) > !!x))

#> # A tibble: 0 x 2
#> # ... with 2 variables: a <dbl>, b <dbl>

Edit: All of this no longer applies. The precedence tree is reorganised so that !!x + !!y etc do the right thing by default. The parentheses are no longer necessary since rlang 0.2.0.


The ! operator has really low precedence. This means that it will apply to most of the expression appearing on its right.

!! x > 3

is implicitly equivalent to:

(!! x > 3)

So you have to help R figure out the right precedence with explicit parentheses:

(!! x) > 3

Note that in most cases if you're unquoting on both sides of an operator, you technically don't have to apply the parentheses on the last one:

(!! x) + (!! y) + z

However that will vary according to often mysterious rules of precedence, so I suggest to always enclose in parentheses when operators are involved:

(!! x ) + (!! y) + (!! z)

You can use filter_at

oof <- function(variables) {
  x <- rlang::sym(variables[[1]])
  df <- data.frame(a = 1, b = 2)
  print(df %>% filter_at(vars(!!x), any_vars(. == !!x)))
  print(df %>% filter(magrittr::equals(!!x, !!x)))
}

I use magrittr::equals to show the magrittr style works as well

oof(c("b"))

#   a b
# 1 1 2
#   a b
# 1 1 2

This is a very generic way of handling any field value condition

data%>%
    filter(!!quo((!!as.name (field1)) > (!!myVal)))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!