我正在使用带有purr的地图的列表-列方法来生成带有ggplot的一系列图(我在printing ggplot with purrr map和她的博客https://aosmith.rbind.io/2018/08/20/automating-exploratory-plots/上都阅读了@aosmith的精彩文章)。但是,我遇到的问题是如何在地图循环内将单个标题传递给这些图。我知道我可以在以后的阶段使用plotgrid之类的东西,或者使用mapply等来做到这一点,但是我想知道为什么当我使用mutate生成图时,为什么它不起作用。
这里是一个例子:
# 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))
这将产生一个指向向量回收问题的错误,但是我的数据列表和myvar向量具有相同的长度。
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.
此外,当我将map2与list-column和带有名称的vector一起使用时,它按预期方式工作...
test <- mtcars %>%
group_by(cyl) %>%
nest()
map2(test$data, myvar, myPlot) # This works
对此行为以及如何在purrr / dplyr方法中进行修复的任何解释将不胜感激:-)
kJ
在ungroup
之后仅nest
:
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() %>%
ungroup() %>%
mutate(plots = map2(data, myvar, myPlot))
#> # A tibble: 3 x 3
#> cyl data plots
#> <dbl> <list> <list>
#> 1 6 <tibble [7 x 10]> <gg>
#> 2 4 <tibble [11 x 10]> <gg>
#> 3 8 <tibble [14 x 10]> <gg>
reprex package(v0.3.0)于2020-06-11创建