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(.))
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