Problem with facet_wrap and curly curly

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

Created on 2019-08-07 by the reprex package (v0.3.0)

Thank you!

1 Like

If you use the newish vars() notation within facet_wrap(), this works.

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`.

Created on 2019-08-07 by the reprex package (v0.3.0)

I really like this blog post, which discusses various strategies for tidy evaluation including a section on "passing the dots"

8 Likes

Ohhh thank you so much!!!!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.