I have two lists, whose elements have partially overlapping names, which I need to merge/combine together into a single list, element by element:
My question is related to Combine/merge lists by elements names, but the data structure in my example is more complicated and thus, the solution provided under the above mentioned link does not work in this case.
Here is a simplified toy example:
l.1 <- list(list(c(10,20), NULL),list(c(10,20,30), NULL), list(c(9,12,13), NULL))
names(l.1) <- c("a","b","c")
l.2 <- list(list(NULL,c(1,0)),list(NULL,c(1,2,3)))
names(l.2) <- c("a","b")
Thus, the data is of type "list in list" and looks like this:
# > l.1
# $a
# $a[[1]]
# [1] 10 20
# $a[[2]]
# NULL
#
# $b
# $b[[1]]
# [1] 10 20 30
# $b[[2]]
# NULL
#
# $c
# $c[[1]]
# [1] 9 12 13
# $c[[2]]
# NULL
#
# > l.2
# $a
# $a[[1]]
# NULL
# $a[[2]]
# [1] 1 0
#
# $b
# $b[[1]]
# NULL
# $b[[2]]
# [1] 1 2 3
The result of merging both lists should look like this:
# $a
# $a[[1]]
# [1] 10 20
# $a[[2]]
# [1] 1 0
#
# $b
# $b[[1]]
# [1] 10 20 30
# $b[[2]]
# [1] 1 2 3
#
# $c
# $c[[1]]
# [1] 9 12 13
# $c[[2]]
# NULL
I already adapted the solution given in Combine/merge lists by elements names, but this seems not to work for this data structure.
Here is what I tried:
l <- list(l.1, l.2)
keys <- unique(unlist(lapply(l, names)))
do.call(mapply, c(FUN=c, lapply(l, `[`, keys)))
I appreciate any help.
Here you go in 3 lines:
This is a kind of a nested merge function which seems to produce the output you desire. I feel like there should be a more simple way but I can't think of one. It will prefer values from the first parameter, but will merge with values from the second parameter if there is a matching name or index.
Here is an additional solution. It uses
mapply
withc
to combine the lists:I adapted this answer from answers found on this SO question on merging two lists and this R help question on how to delete null elements in a list.
The first line gathers the names present in at least one of the two lists (i.e. all possible names). The second line uses
mapply
,c
, and list indexing with the previously gathered names to combine the lists, albeit with extraNULL
entries present. The third line gets rid of theseNULL
entries while preserving list names.Note this answer does get rid of the
NULL
entry for list elementc
.You can use
lapply
operating on the keys to do this merge:Inspired by josilber's answer, here we do not hard-code the length of the sublists and use
lapply
to create them in the result: