i enjoy using purrr’s map and map2 a lot, but i often find myself in the situation of wanting to map more inputs. I know there is also pmap but i don’t really understand how to use it.
Below is my example for creating a pairplot in ggplot2. It is missing the value of name.x as label for the x-axis.
plots = iris%>%
pivot_longer(!Species)%>%
left_join(
iris%>%
pivot_longer(!Species),by="Species"
)%>%
group_by(name.x,name.y)%>%
nest()%>%
mutate(
plots =
map2(
.x=data,.y=name.x,
~ggplot(.x)+
geom_point(aes(value.x,value.y,color=Species))+
xlab(.y)
))
ggarrange(plotlist=plots$plots, common.legend = TRUE, legend="bottom")
I’m looking forward to your suggestions!
It would be ideal if they could be used smoothly in a pipe.
>Solution :
Use pmap like so:
plots <- iris %>%
pivot_longer(!Species)%>%
left_join(iris %>% pivot_longer(!Species), by = "Species")%>%
group_by(name.x, name.y) %>%
nest() %>%
mutate(plots = pmap(
list(data, name.x, name.y),
\(d, x, y) ggplot(d)+
geom_point(aes(value.x, value.y, color = Species))+
xlab(x) + ylab(y)
))
That is:
- Collect the variables you want to map over in a list, so
list(data, name.x, name.y) - Define a function that takes those arguments.
There’s several ways of defining that function. E.g. you could use the formula syntax like you did for map2, with ..1, ..2 and ..3. But I like the new syntax for anonymous functions (i.e. \(x, y)) quite a bit better, since you can name the arguments.