I am trying to build a function for a simple ggplot using the {{}} from the latest version of rlang, but it seems that it doesn't work inside facet_wrap or facet_grid. It doesn't recognize the argument that goes in facet_wrap (. ~ var)
library("rlang")
library("tidyverse")
mtcars %>%
ggplot(aes(wt)) +
geom_histogram() + facet_wrap(. ~cyl)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
histo_cat2 <- function(var1, var2, data = data) {
data %>%
ggplot(aes({{var1}})) +
geom_histogram() +
facet_wrap(. ~ {{var2}})}
histo_cat2(var1 = wt, var2 = cyl, data = mtcars)
#> Error in eval_tidy(facet, data, env): object 'cyl' not found
library(tidyverse)
histo_cat2 <- function(var1, var2, data = data) {
data %>%
ggplot(aes({{ var1 }})) +
geom_histogram() +
facet_wrap(vars({{ var2 }}))
}
histo_cat2(var1 = wt, var2 = cyl, data = mtcars)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
But, depending on the level of complexity you need, you might be able to just "pass the dots" and not deal with quoting and unquoting your faceting variables. This also will enable you to facet by more than one variable like this:
histo_facet_dots <- function(data, x, ...) {
data %>%
ggplot(aes({{ x }})) +
geom_histogram() +
facet_wrap(vars(...))
}
histo_facet_dots(mtcars, x = wt, cyl, am)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.