Using nest and purrr::map outside of mutate

Viewed 1117

Lets say I want to split out mtcars into 3 csv files based on their cyl grouping. I can use mutate to do this, but it will create a NULL column in the output.

library(tidyverse)
by_cyl = mtcars %>% 
           group_by(cyl) %>%
           nest()
by_cyl %>%
  mutate(unused = map2(data, cyl, function(x, y) write.csv(x, paste0(y, '.csv'))))

is there a way to do this on the by_cyl object without calling mutate?

2 Answers

Here is an option using purrr without mutate from dplyr.

library(tidyverse)
mtcars %>%
  split(.$cyl) %>%
  walk2(names(.), ~write_csv(.x, paste0(.y, '.csv')))

Update

This drops the cyl column before saving the output.

library(tidyverse)
mtcars %>%
  split(.$cyl) %>%
  map(~ .x %>% select(-cyl)) %>%
  walk2(names(.), ~write_csv(.x, paste0(.y, '.csv')))

Update2

library(tidyverse)
by_cyl <- mtcars %>% 
  group_by(cyl) %>%
  nest()
by_cyl %>%
  split(.$cyl) %>%
  walk2(names(.), ~write_csv(.x[["data"]][[1]], paste0(.y, '.csv')))

Here's a solution with do and group_by, so if your data is already grouped as it should, you save one line:

mtcars %>%
  group_by(cyl) %>%
  do(data.frame(write.csv(.,paste0(.$cyl[1],".csv"))))

data.frame is only used here because do needs to return a data.frame, so it's a little hack.

Related