我试图从一个嵌套的嵌套框架中的列表列中保存ggplots,文件名中有嵌套变量,这样我就知道哪个图对应于哪个数据.

我使用的方法适用于我从嵌套的数据帧中保存CSV文件,但不适用于ggploy对象.

data("mtcars")
temp_dir <- tempfile()
dir.create(temp_dir)
library(tidyr) # for nest function

plot_fun <- function(x){
  p <- ggplot(data = x, aes(x = wt, y = mpg)) + 
    geom_point()
  return(p)
}

cyl_mtcars <- mtcars %>% 
  nest(data = -cyl) %>% 
  mutate(plots = map(.x = data, .f = plot_fun)
  )
head(cyl_mtcars)

它产生了

# A tibble: 3 × 3
    cyl data               plots 
  <dbl> <list>             <list>
1     6 <tibble [7 × 10]>  <gg>  
2     4 <tibble [11 × 10]> <gg>  
3     8 <tibble [14 × 10]> <gg>

但是当我试着把这些数字保存下来的时候

cyl_mtcars %>% 
  pwalk(
    function(cyl, plots) ggsave(filename = file.path(temp_dir, glue("{cyl}.png")), plot = plots)
    )

我得到这个错误

Error in `pmap()` at purrr/R/pmap.R:148:2:
ℹ In index: 1.
Caused by error in `.f()`:
! unused argument (data = .l[[2]][[i]])
Run `rlang::last_trace()` to see where the error occurred.```

推荐答案

问题是,使用pwalkpmap将所有列传递给函数.由于您的函数只有两个参数,因此您会得到unused argument错误,因为您嵌套的数据有三列.要解决这个问题,可以将...添加到函数参数中:

temp_dir <- tempfile()
dir.create(temp_dir)

library(tidyverse)

plot_fun <- function(x) {
  ggplot(data = x, aes(x = wt, y = mpg)) +
    geom_point()
}

cyl_mtcars <- mtcars %>%
  nest(data = -cyl) %>%
  mutate(plots = map(.x = data, .f = plot_fun))

cyl_mtcars %>% 
  pwalk(
    function(cyl, plots, ...) {
      ggsave(filename = file.path(temp_dir, glue::glue("{cyl}.png")), plot = plots)
    }
  )
#> Saving 7 x 5 in image
#> Saving 7 x 5 in image
#> Saving 7 x 5 in image

R相关问答推荐

高质量地将R格式的图表从Word中输出

在数据表中呈现数学符号

如果索引重复,聚合xts核心数据

基于shiny 应用程序中的日期范围子集xts索引

如何在ggplot 2线性图的每个方面显示每个组的误差条?

从嵌套列表中智能提取线性模型系数

将复杂的组合列表转换为数据框架

如何根据嵌套元素的名称高效而优雅地确定它属于哪个列表?

矩阵的堆叠条形图,条形图上有数字作为标签

使用data.table::fcase()而不是dplyr::case_When()时保持值

提高圣彼得堡模拟的速度

如何将一些单元格的内容随机 Select 到一个数据框中?

ggplot R:X,Y,Z使用固定/等距的X,Y坐标绘制六边形热图

在散点图中使用geom_point放置线图例

在ggploy中创建GeV分布时出错

按镜像列值自定义行顺序

Data.table::Shift type=允许扩展数据(&Q;LAG&Q;)

了解nchar在列表上的意外行为

将R中对象的CSV数组转换为JSON数组

如何从矩阵绘制环弦图