Generate many dataframes splitting a dataset by a variable

Hello,
I'm trying to generate many dataframes using map.
The names of each dataframes are related to the values of one variable.

I wrote this:

mpg %>% 
  split(.$manufacturer) %>% 
  map(~.x)

And I would like to view the dataframes named:

 audi        
chevrolet   
 dodge       
 ford        
 honda       
 hyundai     
 jeep        
 land rover  
 lincoln     
 mercury     
 nissan      
 pontiac     
 subaru      
 toyota      
 volkswagen

On my data panel. It's very simple, but I'm stuck.
As always, thanks for your time and interest.
Have a nice weekend

1 Like

This does the trick

library(purrr)
library(ggplot2) # For the mpg data set

mpg %>% 
    nest_by(manufacturer) %>%
    mutate(data = set_names(list(data), manufacturer)) %>%
    pull(data) %>% 
    list2env(envir = globalenv())
1 Like

Thanks, andresrcs
I'm trying to understand the code, but I can't internalize it well. It seems complex for me, specially when I can get the groups so easily typing nest_by. I'm puzzled how from nesting I need 4 steps to send each group to the global environment.
Again, thanks andresrcs

This is to make a named list so the generated data frames have names according to the manufacturer column.

This step is just for using standard dplyr syntax that I find more human-readable, but it can be eliminated if you use a placeholder to extract the column on the next line. In which case the code would be

mpg %>% 
    nest_by(manufacturer) %>%
    mutate(data = set_names(list(data), manufacturer)) %>%
    list2env(x = .$data, envir = globalenv())

This line is for storing the whole list of data frames into the global environment in one go (not by iteration like with map but by vectorization).

1 Like

Your solution is the only one I found on the internet.
I think my request is rare.
Before closing this thread, I have a small doubt.
What I need to export every dataset as vector?
For example, export subaru$model, subaru$displ,...,subaru$class as Values
Thanks for all

If you fill that strongly about using iteration (purrr functions ) you can do this

mpg %>% 
    nest_by(manufacturer) %>%
    walk2(.x = .$manufacturer, .y = .$data, .f = ~ assign(.x, .y, envir = globalenv()))

Is this what you mean?

mpg %>% 
    nest_by(manufacturer) %>%
    mutate(data = set_names(list(data), manufacturer)) %>%
    map(.x = .$data, .f = as.list) %>% 
    unlist(recursive = FALSE) %>% 
    list2env(envir = globalenv())
1 Like

:clap: :clap: :clap: :clap: ...Incredible.
There is no solution for that task on the web, andresrcs
Now there is one.
Thanks a lot.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.