What is the correct dplyr functional programming syntax for functions with formulas

Viewed 80

I am trying to write a function to dynamically change a variable name using the dplyr functional programming guidance. It works for most tidyverse variable replacements, but not when the function to be evaluated uses a formula.

A plotting example with facet_wrap:

library(dplyr)
library(ggplot2)

mtcars %>%
  ggplot(aes(hp, mpg)) +
  geom_point() +
  facet_wrap(~cyl)

f <- function(wrap_col) {
  mtcars %>%
  ggplot(aes(hp, mpg)) +
  geom_point() +
  facet_wrap(~ {{ wrap_col }})
}

f(cyl)

# Error in eval_tidy(facet, mask) : object 'cyl' not found

I tried the straightforward version above and using the quotes "{{ wrap_col }}" and square brackets. None worked for me

1 Answers

We could use rlang::inject

library(dplyr)
f <- function(wrap_col) {
  mtcars %>%
  ggplot(aes(hp, mpg)) +
  geom_point() +
  facet_wrap(rlang::inject(~ {{ wrap_col }}))
}

-testing

p1 <- mtcars %>%
 ggplot(aes(hp, mpg)) +
 geom_point() +
 facet_wrap(~cyl)

p2 <- f(cyl)
all.equal(p1, p2)
#[1] TRUE
Related