在函数中使用嵌套变量

Using nesting variable inside a function

是否可以在 purrr::map 中使用的函数中使用嵌套变量? 例如,在下面的示例中,我希望每个绘图都有一个显示气缸数的标题

    library(tidyverse)
    plot_mtcars <- function(df, cyl){
                ggplot(aes(x = disp, y = mpg), data = df) + 
                        geom_point() +
                        ggtitle(paste("Cylinders =", cyl))
            }
    plots <- mtcars %>% 
                nest(-cyl) %>% 
                mutate(plot = map(data, ~plot_mtcars(., cyl)))

上面的代码不起作用,因为所有图 return: Cylinders = 6 (而不是 6、4、8)

这里的问题是cyl是一个向量,所以它在ggtitle中设置了一个字符向量,在这种情况下只使用第一个元素;需要循环cyl,将对应的元素传给plot函数:

plots <- mtcars %>% 
    nest(-cyl) %>% 
    # here use map2 to pass data and corresponding cyl to the plot function
    mutate(plot = map2(data, cyl, ~ plot_mtcars(.x, .y)))

查看剧情标题:

plots$plot[[1]]$labels$title
# [1] "Cylinders = 6"

plots$plot[[2]]$labels$title
# [1] "Cylinders = 4"

plots$plot[[3]]$labels$title
# [1] "Cylinders = 8"