Help with names of list of dataframes using content from a variable

Hi All,

I am trying to name the list with the content of a column as the list was based on filter on that column. No changes in data itself, change would be just renaming list based on column content that it was filtered upon.
Is this doable?

library(tidyverse)

# Example data
df <- mtcars%>%
  mutate(cyl = recode(cyl, "4" = "cyl 4", "6" = "cyl 6", "8" = "cyl 8")) %>%
  group_by(cyl) %>%
  group_split()

# Attempt with Incorrect Result. 
# I am looking for Cyl 4 as an example to be list 1's name , Cyl 6 as name for List2 and so on.

list_name_fn <- function(df){
  df[[1]] <- df$cyl[1]  
}

map(df, ~list_name_fn(.))

Thank you all!

Hello, this solution provides what you are looking for, assuming all the data in the cyl column is the same.

library(tidyverse)

# Example data
df <- mtcars%>%
  mutate(cyl = recode(cyl, "4" = "cyl 4", "6" = "cyl 6", "8" = "cyl 8")) %>%
  group_by(cyl) %>%
  group_split()

# Attempt with Incorrect Result. 
# I am looking for Cyl 4 as an example to be list 1's name , Cyl 6 as name for List2 and so on.

#Using select and distinct to return the names desired for the list. 
list_name_fn <- function(df){
  
  name_for_list= df %>% select(cyl) %>% distinct()
  
}

#Passing the list that contains the dataframes into the list_name_fn using map.  Names will be stored
#as a list, using unlist to create a vector with the names for the list.
names_for_list= map(df,list_name_fn) %>% unlist() 

#Renaming List 
names(df) = names_for_list 
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
l <- mtcars %>%
  mutate(cyl = recode(cyl, "4" = "cyl 4", "6" = "cyl 6", "8" = "cyl 8")) %>%
  group_by(cyl) %>%
  group_split()

names(l) <- paste0('cyl_',c(4,6,8))
l$cyl_4 |> head()
#> # A tibble: 6 × 11
#>     mpg cyl    disp    hp  drat    wt  qsec    vs    am  gear  carb
#>   <dbl> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1  22.8 cyl 4 108      93  3.85  2.32  18.6     1     1     4     1
#> 2  24.4 cyl 4 147.     62  3.69  3.19  20       1     0     4     2
#> 3  22.8 cyl 4 141.     95  3.92  3.15  22.9     1     0     4     2
#> 4  32.4 cyl 4  78.7    66  4.08  2.2   19.5     1     1     4     1
#> 5  30.4 cyl 4  75.7    52  4.93  1.62  18.5     1     1     4     2
#> 6  33.9 cyl 4  71.1    65  4.22  1.84  19.9     1     1     4     1

Created on 2023-10-12 with reprex v2.0.2

Thanks @bcavinee !
This is great! I am trying to use map wherever possible and couldn't think of using a vector for names.
Thanks!

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.