我有一些关于purrr :: pmap的问题,可以在nested.data.frame中制作多个ggplot图.
我可以通过使用purrr :: map2在代码下运行而没有问题,我可以在nested.data.frame中创建多个图(2个图).
作为一个例子,我在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)))
但是,当我想绘制超过2个图时,我无法解决使用purrr :: pmap,如下面的代码.
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
有没有办法在nested.data.frame中解决这个问题?请给我一些建议或答案.
r2e*_*ans 18
purrr::pmap 采用(至少)两个参数:
 pmap(.l, .f, ...)
哪里
  .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.
此外,.x和.y很好的工作只有两个参数,但(在同一手册页),它说For more arguments, use '..1', '..2', '..3' etc.
为了便于阅读(并且效率稍高),我将所有单独的调用mutate合并为一个; 如果需要,你可以将它们分开(特别是如果代码中的代码多于你在这个简化示例中显示的代码):
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))
  )