How do incoporate arguments in functions into ggplot2/dplyr conventions

时间:2015-05-24 22:00:55

标签: r ggplot2 dplyr

Sorry for the poorly worded question but I think this might be a common issue that I haven't found an answer for.

ggplot/dplyr don't use character types to call the column name to filter/group by:

library(dplyr)
library(ggplot2)
mtcars %>%
      filter(gear > 4)

#OR
enter code here


ggplot(data = mtcars, aes(x = disp, y = wt, color = factor(gear))) + geom_point()

...so if wanted to build a function that would use these non-character types to say change gear to a different column, how would I do that? Do I need to call assign?

Here's a hacky solution to filtering that may help clarify my question:

filter_foo <- function(data, column, value) {
  data[column > value,]
}

filter_foo(mtcars, mtcars$gear , 4) 

1 个答案:

答案 0 :(得分:1)

With the Help of Henrik in comments of my post and this SO question, I've learned that what I am interested in is applying non-standard evaluation for dplyr/ggplot2. And a recreation of the results I want below using character vectors.

library(lazyeval)
library(ggplot2)
library(dplyr)
filter_criteria <- interp(~ which_column > 4, which_column = as.name("gear"))
mtcars %>%
  filter_(filter_criteria)

#OR 
ggplot(data = mtcars, aes_string(x = "disp", y = "wt", color = "factor(gear)")) + geom_point()