Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

'unused argument' error when using `purrr::pwalk` to save ggplots from list column in nested dataframe

I’m trying to save out ggplots from a list column in a nested dataframe with the nesting variable in the filename so that I know which plot corresponds to which data.

I’m using an approach which worked for me saving csv files from nested dataframes, but doesn’t work with ggplot objects.

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)

Which produces

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# 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>

But when I try to save the figures out

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

I get this error

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.```

>Solution :

The issue is that using pwalk or pmap all columns are passed to the function. And as your function has only two arguments you get an unused argument error as you nested data has three columns. To fix that, you could add ... to the function arguments:

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading