3

The title describes pretty much what I want:

instead of:

filter(mtcars, cyl == 8)

I would like to use:

var <- "cyl"
filter(mtcars, var == 8)  # pseudocode

just like

mtcars[which(mtcars[,var]==8),]

I see that there are functions like starts_with() but IMHO none really suits for above rather simple application.

Janhoo
  • 597
  • 5
  • 21
  • just saw that this is somewhat related to http://stackoverflow.com/questions/21208801/group-by-multiple-columns-in-dplyr-using-string-vector-input – Janhoo Aug 01 '14 at 07:58
  • It's not currently supported, but I'm working on it: https://github.com/hadley/dplyr/issues/352 – hadley Aug 01 '14 at 13:30
  • This feature is now implemented. No workaround neccessary. To get around non-standard evaluation, use the `manip_()` flavor, e.g. `filter_()`. `vignette("nse")` elaborates on that. Thanks @hadley – Janhoo Oct 20 '15 at 12:34

3 Answers3

3

Try this:

mtcars %>% do(filter(., .[[var]] == 8))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
2
eval(substitute(filter(mtcars, var == 8),list(var=as.name(var))))%>%
head(2)
#    mpg cyl disp  hp drat   wt  qsec vs am gear carb
# 1 18.7   8  360 175 3.15 3.44 17.02  0  0    3    2
# 2 14.3   8  360 245 3.21 3.57 15.84  0  0    3    4

filter(mtcars, get(var, envir=as.environment(mtcars)) == 8) #should also work but not recommended
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Here's one more way with do.call:

do.call(filter, list(mtcars, bquote(.(as.name(var)) == 8)))
Matthew Plourde
  • 43,932
  • 7
  • 96
  • 113