我有两个列表,其元素具有部分重叠的名称,我需要逐个元素地合并/组合成一个列表:
我的问题与按元素名称组合/合并列表有关,但我的示例中的数据结构更复杂,因此,在这种情况下,上述链接下提供的解决方案不起作用.
这是一个简化的玩具示例:
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")
Run Code Online (Sandbox Code Playgroud)
因此,数据的类型为"list in list",如下所示:
# > 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]]
# …Run Code Online (Sandbox Code Playgroud) 假设我有N个列表,它们都具有相同的列名.我想合并这些,以便我得到一个具有相同列的结果列表,但现在包含所有N列表中的条目.这是一个显示我想要的MWE:
ls<-list()
ls[[1]]<-list("a"=1,
"b"=2)
ls[[2]]<-list("a"=3,
"b"=4)
#how to write a one-liner that produces lsTotal, which is the union of ls[[1]] and ls[[2]]?
lsTotal<-list("a"=c(1,3),
"b"=c(2,4))
Run Code Online (Sandbox Code Playgroud)
我发现了这个线程,我可以使用它Map(c, ls[[1]], ls[[2]]).然而,如果ls很长的话,写出来是很乏味的.有捷径吗?
我想合并两个列表以保留每个对象的索引:
mylist<-list(1,NULL,2)
otherlist<-list(NULL,3,NULL,4,5,6)
# Desired
list(1,3,2,4,5,6)
# my try:
suppressWarnings(mapply(c, mylist, otherlist) )
Run Code Online (Sandbox Code Playgroud)
答案应该是普遍的
编辑:为了避免类似问题的扩散。我决定在这里也请求保留属性的可能性(最好是带有基数)。
mylist<-list(1,NULL,2)
attr(mylist[[1]],"at")<-"a"
attr(mylist[[3]],"at")<-"c"
otherlist<-list(NULL,3,NULL,4,5,6)
attr(otherlist[[2]],"at")<-"b"
attr(otherlist[[4]],"at")<-"d"
attr(otherlist[[5]],"at")<-"e"
attr(otherlist[[6]],"at")<-"f"
Run Code Online (Sandbox Code Playgroud) 给定一个列表列表,是否有一种优雅的方式将原始转换为处理?我使用简单的值,如1,2,3,但值可能是数据帧或其他.目标不是重复删除每个唯一命名的内容,只需通过合并内容来重复删除名称.
original = structure(list(name1 = structure(list(one = 1, two = 2, three = 3), .Names = c("one",
"two", "three")), name2 = structure(list(a = 9), .Names = "a"),
name1 = structure(list(four = 4, five = 5, six = 6), .Names = c("four",
"five", "six")), name2 = structure(list(b = 8), .Names = "b")), .Names = c("name1",
"name2", "name1", "name2"))
treated = structure(list(name1 = structure(list(one = 1, two = 2, three = 3,
four = 4, five = 5, six = 6), .Names …Run Code Online (Sandbox Code Playgroud)