Combine/merge lists by elements names (list in list)

前端 未结 5 900
渐次进展
渐次进展 2021-01-11 20:42

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 rela

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-11 21:05

    Here is an additional solution. It uses mapply with c to combine the lists:

    ## get all possible names
    l.names <- union(names(l.1), names(l.2)) 
    ## combine lists
    r <- mapply(c, l.1[l.names], l.2[l.names]) 
    ## get rid of NULL entries
    l.3 <- sapply(names(r), 
                  function(x) r[[x]][!sapply(r[[x]], is.null)], USE.NAMES=TRUE)
    

    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 extra NULL entries present. The third line gets rid of these NULL entries while preserving list names.

    Note this answer does get rid of the NULL entry for list element c.

提交回复
热议问题