Passing strings as arguments in dplyr verbs

andrey picture andrey · Jul 7, 2014 · Viewed 7.3k times · Source

I would like to be able to define arguments for dplyr verbs

condition <- "dist > 50"

and then use these strings in dplyr functions :

require(ggplot2)
ds <- cars
ds1 <- ds %>%
   filter (eval(condition))
ds1

But it throws in error

Error: filter condition does not evaluate to a logical vector. 

The code should evaluate as:

  ds1<- ds %>%
     filter(dist > 50)
  ds1

Resulting in :

ds1

   speed dist
1     14   60
2     14   80
3     15   54
4     18   56
5     18   76
6     18   84
7     19   68
8     20   52
9     20   56
10    20   64
11    22   66
12    23   54
13    24   70
14    24   92
15    24   93
16    24  120
17    25   85

Question:

How to pass a string as an argument in a dplyr verb?

Answer

hadley picture hadley · Jul 10, 2014

In the next version of dplyr, it will probably work like this:

condition <- quote(dist > 50)

mtcars %>%
   filter_(condition)