Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using nest and purrr::map outside of mutate

Tags:

r

dplyr

purrr

tidyr

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?

like image 544
kmace Avatar asked Sep 28 '17 01:09

kmace


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')))
like image 115
www Avatar answered Oct 08 '22 19:10

www


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.

like image 21
Moody_Mudskipper Avatar answered Oct 08 '22 19:10

Moody_Mudskipper