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?
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
To make the ~ .x
work, do an evaluation with !!
quos(hp, am) %>%
walk(~ print(make_plot(!! .x)))