1

I would like to parameterize the filter function of dplyr. For e.g Instead of

mtcars %>% filter(mpg <20)

I would like a function where I can pass the column index so that I can do

a <- c(4,6)
df <- mtcars %>% filter(cyl %in% a) #- This works

But

df <- mtcars %>% filter_("cyl %in% a") #Gives 'a' not found

and

  df <- mtcars %>% filter_("cyl %in% 'a'") # gives 0 rows

I will be using a variable where I am using "cyl". What am I missing?

Tinniam V. Ganesh
  • 1,979
  • 6
  • 26
  • 51
  • 1
    Could you let me know which question it is a duplicate of? – Tinniam V. Ganesh Apr 12 '17 at 04:39
  • The duplicates are listed above your question. – MrFlick Apr 12 '17 at 04:45
  • As of now I have abandoned the filter method of dplyr and subset the data frame and loop through the values in the vector 'a'. It is slow, but it works. If it can be done with dplyr and filter that would help – Tinniam V. Ganesh Apr 12 '17 at 05:46
  • FWIW with the new rlang NSE backend in the devel version, you could do `mtcars %>% filter(eval_tidy(parse_expr(names(mtcars)[1])) > 20)` (whose `eval(parse(...))` echo makes me nervous) or simply `mtcars %>% filter(get(names(mtcars)[1]) > 20)`, though I'm not sure that's robust or recommended. A better option might be the new pronoun structure: `mtcars %>% filter(.data[[names(mtcars)[1]]] > 20)` – alistaire Apr 12 '17 at 05:47
  • You could do something like this: `mtcars %>% filter_(lazyeval::interp(~col %in% a, col=as.name("cyl")))` – MrFlick Apr 12 '17 at 15:01
  • MrFlick- Your solution works great! Sorrry for the delay.Please answers and I wil accept. Thanks Ganesh – Tinniam V. Ganesh Apr 17 '17 at 03:58

0 Answers0