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

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

问题描述

我有一个列表,该列表由另外两个列表组成,它们的元素具有部分重叠的名称,我需要将每个元素逐个合并/合并为一个列表.

I have one list which consists of another two lists, whose elements have partially overlapping names, which I need to merge/combine together into a single list, element by element.

>按元素名称组合/合并列表(在list)提供了一种解决方案,如果两个列表是单独的对象,即不是嵌套(再次)嵌套在单个列表中,则如何解决此问题.

In Combine/merge lists by elements names (list in list) a solution is provided how to solve this problem if the two lists are separate objects, i.e. not nested (again) in one single list.

这里是示例的总结

# Generate some toy data    
library(digest)    
l.1 <- rep(list(list(c(10,20), NULL),
                list(c(10,20,30), NULL), 
                list(c(9,12,13), NULL)), 10000)
names(l.1) <- sapply(sample(1:30000, 30000, replace=FALSE), digest)
l.2 <- rep(list(list(NULL,c(1,0)),
                list(NULL,c(1,2,3))), 10000)
names(l.2) <- c(names(l.1)[1:10000], sapply(sample(30001:40000, 10000, replace=FALSE), digest))


# Apply the solution posted at
# https://stackoverflow.com/questions/23483421/combine-merge-lists-by-elements-names-list-in-list
keys <- unique(c(names(l.1), names(l.2)))
l  <- 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)

如上所述,当单独列表的数量(此处为2个)很小时,此解决方案很方便.

As stated above this solution is convenient when the number of separate lists (here 2) is small.

将这些列表嵌套在一个列表中的情况更为现实.这样,一个人便可以对所有嵌套列表执行该操作.有2个嵌套列表还是300个嵌套列表都没关系.

A scenario where those lists are nested within one single list is more realistic. Thus, one would be then able to perform the operation for all nested lists. It would not matter if there are 2 nested lists or 300.

例如:

l.new <- list(l.1, l.2)

要修改上述解决方案,我知道第一行必须更改为:

To modify the solution above I know that the first line has to changed to:

keys <- unique(unlist(lapply(l.new, names)))

但是我不知道如何适应第二行

However I don't know how to adapt the second line

l  <- 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)

感谢您的帮助.

推荐答案

您只需将lapply与用户定义的函数一起使用两次,即可:

You just need to use lapply two more times with user-defined functions:

keys <- unique(unlist(lapply(l.new, names)))
l2  <- setNames(lapply(keys, function(key) {
  len <- max(unlist(lapply(l.new, function(x) length(x[[key]]))))
  lapply(seq(len), function(i) unlist(lapply(l.new, function(x) x[[key]][[i]])))
}), keys)
all.equal(l, l2)
# [1] TRUE

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

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