Nienke Mekkes
Nienke Mekkes

Reputation: 87

combine elements of list of lists with the same name

I have a list of 4 lists with the same name:

lst1 <- 
list(list(c(1,2,3)),list(c(7,8,9)),list(c(4,5,6)),list(c(10,11,12)))
names(lst1) <- c("a","b","a","b")

I want to combine the sub lists together (first "a" with second "a", first "b" with second "b":

result <- list(list(c(1,2,3,4,5,6)),list(c(7,8,9,10,11,12)))
names(result) <- c("a","b")

I have tried multiple things, but can't figure it out.

Upvotes: 3

Views: 1474

Answers (3)

markus
markus

Reputation: 26343

Another option is to use unlist first and then split the resulting vector.

vec <- unlist(lst1)
split(unname(vec), sub("\\d+$", "", names(vec)))
#$a
#[1] 1 2 3 4 5 6

#$b
#[1]  7  8  9 10 11 12

Upvotes: 3

nicola
nicola

Reputation: 24480

Just group the elements with the same name and unlist them:

tapply(lst1,names(lst1),FUN=function(x) unname(unlist(x)))

Upvotes: 2

Julius Vainora
Julius Vainora

Reputation: 48211

Since lst1["a"] isn't going to give us all the elements of lst1 named a, we are going to need to work with names(lst1). One base R approach would be

nm <- names(lst1)
result <- lapply(unique(nm), function(n) unname(unlist(lst1[nm %in% n])))
names(result) <- unique(nm)
result
# $a
# [1] 1 2 3 4 5 6
#
# $b
# [1]  7  8  9 10 11 12

Upvotes: 4

Related Questions