2

Given the following type of function:

library(tidyverse)

make_plot <- function(var) {
  quo_var <- enquo(var)
  ggplot(mtcars, aes(x = !!quo_var, y = mpg)) +
    geom_point()
}

I would like to call this on various columns of a data.frame like this:

make_plot(hp)
make_plot(am)
...

But to keep the code DRY, I would like to use purrr::map or purrr::walk, but the following does not work:

list(hp, am) %>%
  map(make_plot)

I have also tried list("hp", "am") %>% map(make_plot(sym(.)) which also does not work. What is the correct approach here for using a list of strings or variables?

JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116
  • You need `alist()` instead of `list()`. See also this https://stackoverflow.com/a/49834499/786542 – Tung Apr 03 '19 at 17:24

1 Answers1

2

We can wrap with quote to avoid the early evaluation

library(tidyverse)
library(ggplot2)
list(quote(hp), quote(am)) %>% 
      map(make_plot)

Or another option is to pass it as list of quosure (quos)

quos(hp, am) %>%
    map(make_plot)

-last plot

enter image description here


To make the ~ .x work, do an evaluation with !!

quos(hp, am) %>%
            walk(~ print(make_plot(!! .x)))
akrun
  • 874,273
  • 37
  • 540
  • 662