Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@eddjberry
Created August 14, 2018 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eddjberry/6dcda168c52204e27b91fbfc0ffdb246 to your computer and use it in GitHub Desktop.
Save eddjberry/6dcda168c52204e27b91fbfc0ffdb246 to your computer and use it in GitHub Desktop.
Create separate csv files of the data for each level of some categorical column
library(tidyverse)
# Nest iris by Species
iris_nest <- iris %>%
group_by(Species) %>%
nest()
# Get the data list and set the names of the list to Species
# write_csv for each df in the data list with its name as the filename
iris_nest %>%
pull(data) %>%
set_names(iris_nest$Species) %>%
walk2(names(.), ~ write_csv(.x, path = str_c('data/', .y, '.csv')))
# Another way to do the nesting is
iris %>%
nest(-Species)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment