按元素名称合并/合并列表(列表中的列表) [英] Combine/merge lists by elements names (list in list)

查看:169
本文介绍了按元素名称合并/合并列表(列表中的列表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表,其元素具有部分重叠的名称,我需要将每个元素逐个合并/合并为一个列表:

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

合并两个列表的结果应如下所示:

# $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.

这是我尝试过的:

l <- list(l.1, l.2)
keys <- unique(unlist(lapply(l, names)))
do.call(mapply, c(FUN=c, lapply(l, `[`, keys)))

感谢您的帮助.

推荐答案

受josilber的回答启发,此处我们不对子列表的长度进行硬编码,而是使用lapply在结果中创建它们:

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:

keys <- unique(c(names(l.1), names(l.2)))
setNames(lapply(keys, function(key) {
    l1 <- l.1[[key]]
    l2 <- l.2[[key]]
    len <- max(length(l1), length(l2))

    lapply(seq(len), function(i) c(l1[[i]], l2[[i]]))
  }),
  keys)

这篇关于按元素名称合并/合并列表(列表中的列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆