1

For the following scenario I get an empty data frame

D = data.frame(X = c("x1", "x2", "x3"))
vals = c("x1", "x2")
col = "X"
dplyr::filter(D, col %in% vals)

But doing it as following works

dplyr::filter(D, X %in% vals)

I cannot hardcode the name of the column nor the values by which to filter. I need the first scenario to work.

Devaraj Phukan
  • 196
  • 1
  • 9
  • @tmfmnk there is a slight difference in the questions, in this question we are trying to filter rows on multiple values. But the solutions in both questions should work by changing the filtering with `==` or `%in%` ? – Devaraj Phukan Jul 30 '19 at 13:35
  • 1
    Sure, it is working. You can do `filter(D, !!as.name(col) %in% vals)` or `filter(D, UQ(as.name(col)) %in% vals)`. – tmfmnk Jul 30 '19 at 13:38

1 Answers1

3

We can convert to symbol and evaluate (!!)

dplyr::filter(D, !! rlang::sym(col) %in% vals)
#    X
#1 x1
#2 x2

Or another option is filter_at

D %>%
    filter_at(vars(col), any_vars(. %in% vals))
akrun
  • 874,273
  • 37
  • 540
  • 662