I am using a list-columns approach with purr's map to generate series of plots with ggplot (I did read @aosmith's excellent posts both here printing ggplot with purrr map and on her blog https://aosmith.rbind.io/2018/08/20/automating-exploratory-plots/). However, where I am stuck is with how to pass individual titles to these plots right within the map loop. I know I can do it at a later stage with plotgrid and such, or with a mapply etc., but I was wondering why it doesn't work when I do it at the moment of plot generation with mutate.
Here is an example:
# Note that I am using dplyr 1.0.0 and R 4.0
library(tidyverse)
# Vector with names for the plots
myvar <- c("cylinderA", "cylinderB", "cylinderC")
myvar <- set_names(myvar)
# Function to plot the plots
myPlot <- function(dataaa, namesss){
ggplot(data = dataaa) +
aes(x = disp, y = qsec) +
geom_point() +
labs(title = namesss)
}
# List-columns with map2 to iterate over split dataframe and the vector with names
mtcars %>%
group_by(cyl) %>%
nest() %>%
mutate(plots = map2(data, myvar, myPlot))
This produces an error pointing to a vector recycling problem, but my data list and myvar vector have the same length.
Error: Problem with `mutate()` input `plots`. x Input `plots` can't be recycled to size 1. ℹ Input `plots` is `map2(data, myvar, myPlot)`. ℹ Input `plots` must be size 1, not 3. ℹ The error occured in group 1: cyl = 4.
Also, when I use map2 on its own with the list-column and my vector with names, it works as expected...
test <- mtcars %>%
group_by(cyl) %>%
nest()
map2(test$data, myvar, myPlot) # This works
Any explanations of this behaviour and how to fix it within the purrr/dplyr approach would be much appreciated :-)
kJ