Search code examples
rlistnames

In R list ,how to set sub list names


How to set list names ,here is the code as below. Currently,split_data include two sub list [[1]] and [[2]], how set names separately for them? I want set name 'A' for [[1]],'B' for [[2]], so can retrieve data use split_data['A']... Anyone can help on this, thanks ? for instance ma <- list(a=c('a1','a2'),b=c('b1','b2')) can use ma["a"] for sub list

library(tidyverse)
test_data <- data.frame(category=c('A','B','A','B','A','B','A','B'),
                        sales=c(1,2,4,5,8,1,4,6))

split_data <- test_data %>% group_split(category)

Solution

  • Others have shown you in the comments how to get what you want using split() instead of group_split(). That seems like the easiest solution.

    However, if you're stuck with the existing code, here's an alternative that keeps your current code, and adds the names.

    library(tidyverse)
    test_data <- data.frame(category=c('A','B','A','B','A','B','A','B'),
                            sales=c(1,2,4,5,8,1,4,6))
    
    split_data <- test_data %>% group_split(category)
    
    
    names(split_data) <- test_data %>% group_by(category) %>% group_keys() %>% apply(1, paste, collapse = ".")
    

    The idea is to use group_by to split in the same way group_split does, then extract the keys as a tibble. This will have one row per group, but will have the different variables in separate columns, so I put them together by pasting the columns with a dot as separator. The last expression in the pipe is equivalent to apply(keys, 1, f) where f is function(row) paste(row, collapse = "."). It applies f to each row of the tibble, producing a single name.

    This should work even if the split happens on multiple variables, and produces names similar to those produced by split().