Subset the list by its names to groups and keep these groups as list so that the original list will be list of lists in R

Viewed 166

I have a list of seven elements. The names of this list are (a,a,b,b,b,a,b) each element is a data frame of same columns names and with a different number of rows. I want my list to be the list of lists. e.g.,

original.list<-list(a=data.frame(x=c(1:5), y=c(1:5)),a=data.frame(x=c(1:15), y=c(15:29)),b=data.frame(x=rep(5,10), y=rep(-1,10)), b=data.frame(x=c(1:7), y=c(1:7)),b=data.frame(x=c(2:8), y=c(1:7)),a=data.frame(x=c(10:50), y=c(10:50)),b=data.frame(x=rep(1.2,14), y=rep(10,14)))

 new.list<- list(a=list(original.list[[1]],original.list[[2]],original.list[[6]]),b=list(original.list[[3]],original.list[[4]],original.list[[5]],original.list[[7]]))
3 Answers

You can split the original list by name (and afterwards unname the sublists):

lapply(split(original.list, names(original.list)), unname)

Result is as new.list:

identical(new.list, lapply(split(original.list, names(original.list)), unname))
[1] TRUE

You can extract the names of the list and iteratively select one name at a time using lapply :

nm <- names(original.list)
lapply(unique(nm), function(x) original.list[nm == x])

We can use map from purrr

library(purrr)
nm <- unique(names(original.list))
map(nm, ~ original.list[names(original.list) == .x])
Related