How to use purrr :: pmap to build multiple ggplot in nested.data.frame file

I have some questions about purrr :: pmap to make some ggplot plots in the nested.data.frame file.

I can run the code below without problems using purrr :: map2, and I can do multiple (2 graphics) in the nested.data.frame file.

As an example, I used the aperture dataset in R.

library(tidyverse) iris0 <- iris iris0 <- iris0 %>% group_by(Species) %>% nest() %>% mutate(gg1 = purrr::map(data, ~ ggplot(., aes(Sepal.Length, Sepal.Width)) + geom_point())) %>% mutate(gg2 = purrr::map(data, ~ ggplot(., aes(Sepal.Length, Petal.Width)) + geom_point())) %>% mutate(g = purrr::map2(gg1, gg2, ~ gridExtra::grid.arrange(.x, .y))) 

But, when I want to build more than 2 graphs, I cannot solve using purrr :: pmap, as shown below.

 iris0 <- iris0 %>% group_by(Species) %>% nest() %>% mutate(gg1 = purrr::map(data, ~ ggplot(., aes(Sepal.Length, Sepal.Width)) + geom_point())) %>% mutate(gg2 = purrr::map(data, ~ ggplot(., aes(Sepal.Length, Petal.Width)) + geom_point())) %>% mutate(gg3 = purrr::map(data, ~ ggplot(., aes(Sepal.Length, Petal.Length)) + geom_point())) %>% mutate(g = purrr::pmap(gg1, gg2,gg3, ~ gridExtra::grid.arrange(.x, .y, .z))) > Error in mutate_impl(.data, dots) : Index 1 is not a length 1 vector 

Is there a way to solve this problem in the nested.data.frame file? Please give me some tips or answers.

+7
r ggplot2 purrr
source share
1 answer

purrr::pmap takes (at least) two arguments:

  pmap(.l, .f, ...) 

Where

  .l: A list of lists. The length of '.l' determines the number of arguments that '.f' will be called with. List names will be used if present. .f: A function, formula, or atomic vector. 

In addition, .x and .y only work well for two arguments, but (on the same page of the manual) says For more arguments, use '..1', '..2', '..3' etc

For readability (and low efficiency), I will combine all individual calls with mutate into one; you can leave them separate if necessary (esp if there is more code in this example than what is shown in this example):

 library(dplyr) library(tidyr) library(purrr) library(ggplot2) iris0 <- iris %>% group_by(Species) %>% nest() %>% mutate( gg1 = purrr::map(data, ~ ggplot(., aes(Sepal.Length, Sepal.Width)) + geom_point()), gg2 = purrr::map(data, ~ ggplot(., aes(Sepal.Length, Petal.Width)) + geom_point()), gg3 = purrr::map(data, ~ ggplot(., aes(Sepal.Length, Petal.Length)) + geom_point()), g = purrr::pmap(list(gg1, gg2, gg3), ~ gridExtra::grid.arrange(..1, ..2, ..3)) ) 
+8
source share

All Articles