In R, is there a simplar way of saving plots and sheets from nested data?

Viewed 32

Let's say I have the following dataset, with sheets and plots that I want to save one-by-one:

library(tidyverse)

data_set <- iris %>%
  nest(data = -Species) %>%
  mutate(
    plot = map(
      data,
      ~ ggplot(., aes(x = Sepal.Length, y = Sepal.Width)) +
        geom_point()
    )
  )

Currently, if I want to save data_set$plot and data_set$data, I have to do it separately:

# save plots
data_set %>%
  {
    walk2(
      .$Species, .$plot,
      ~ ggsave(
        filename = paste0(.x, ".png"),
        plot = .y
      )
    )
  }

# save sheets    
data_set %>%
  {
    walk2(
      .$Species, .$data,
      ~ write.csv(
        .y,
        paste0(.x, ".csv")
      )
    )
  }

Question:

Is there a way of doing this in the same pipeline? Something like:

data_set %>%
  {
    # plot saving function
  } %>%
  {
    # sheet saving function
  }

or even

data_set %>%
  pivot_longer(
    !Species,
    names_to = "set",
    values_to = "them_all"
  ) %>%
  {
    # one function to save them_all
  }
1 Answers

You can use the pwalk() function in {purrr}

purrr::pwalk(
  .l = list(species = data_set$Species,
            data = data_set$data,
            plot = data_set$plot),
  .f = function(species, data, plot){
    write.csv(data, paste0(species, ".csv"))
    ggsave(filename = paste0(species, ".png"), plot = plot)
  }
)
Related