我试图从嵌套数据框中的列表列中保存ggplots,并在文件名中使用嵌套变量,以便我知道哪个图对应于哪个数据。
我使用的方法适用于从嵌套数据帧保存 csv 文件,但不适用于 ggplot 对象。
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.```
此错误反映了
pwalk()
尝试使用数据框中的所有列。您的匿名函数仅接受两个参数,但由于数据框中有三列,因此传递了三个参数 - 因此出现错误。
您可以通过添加
...
来吸收未使用的列来解决此问题。
cyl_mtcars %>%
pwalk(
function(cyl, plots, ...) ggsave(filename = file.path(temp_dir, glue("{cyl}.png")), plot = plots)
)