Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

purrr mapping more than two variables (for making a pairplot with ggplot)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading