Is it possible to use a nesting variable inside a function used in purrr::map?
For example, in the following example I want each plot to have a title showing the number of cylinders
library(tidyverse)
plot_mtcars <- function(df, cyl){
ggplot(aes(x = disp, y = mpg), data = df) +
geom_point() +
ggtitle(paste("Cylinders =", cyl))
}
plots <- mtcars %>%
nest(-cyl) %>%
mutate(plot = map(data, ~plot_mtcars(., cyl)))
The code above does not work, as all plots return:
Cylinders = 6
(instead of 6,4,8)