如何基于对象索引合并两个列表-保留属性? [英] How to merge two lists based on object indices - keeping attributes?
本文介绍了如何基于对象索引合并两个列表-保留属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想合并两个列表,保留每个对象的索引:
I want to merge two lists keeping the index of each object:
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) )
答案应该是普遍的
为了避免类似问题的泛滥.我决定在这里要求保留属性(最好是保留基数)的可能性.
In order to avoid proliferation of similar questions. I decided to request here also the possibility of keeping attributes (preferably with base).
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"
推荐答案
这里是一个选项,其中我们使用lengths
创建逻辑索引(当存在NULL
时将返回0),并使用mylist
不公开
Here is an option where we create a logical index with lengths
(which will return 0 when there is NULL
) and use to assign the elements with mylist
unlisted
otherlist[lengths(otherlist) == 0] <- unlist(mylist)
otherlist
#[[1]]
#[1] 1
#[[2]]
#[1] 2
#[[3]]
#[1] 3
#[[4]]
#[1] 4
#[[5]]
#[1] 5
#[[6]]
#[1] 6
如果需要使用Map
,请确保相应元素的lengths
相同
If we need to use Map
, make sure the lengths
are the same for the corresponding elements
otherlist[seq_along(mylist)] <- Map(c, otherlist[seq_along(mylist)], mylist)
更新
对于更新后的示例
Update
For the updated example
i1 <- sapply(otherlist, is.null)
i2 <- !sapply(mylist, is.null)
otherlist[i1] <- mylist[i2]
otherlist
#[[1]]
#[1] 1
#attr(,"at")
#[1] "a"
#[[2]]
#[1] 3
#attr(,"at")
#[1] "b"
#[[3]]
#[1] 2
#attr(,"at")
#[1] "c"
#[[4]]
#[1] 4
#attr(,"at")
#[1] "d"
#[[5]]
#[1] 5
#attr(,"at")
#[1] "e"
#[[6]]
#[1] 6
#attr(,"at")
#[1] "f"
这篇关于如何基于对象索引合并两个列表-保留属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文