如何根据对象索引合并两个列表 - 保持属性?

Fer*_*oao 8 attributes r

我想合并两个列表以保留每个对象的索引:

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)

akr*_*run 2

这是一个选项,我们创建一个逻辑索引lengths(当存在时返回 0 NULL)并使用mylist未列出的元素分配元素

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
Run Code Online (Sandbox Code Playgroud)

如果我们需要使用Map,请确保lengths相应元素相同

otherlist[seq_along(mylist)] <- Map(c, otherlist[seq_along(mylist)], mylist)
Run Code Online (Sandbox Code Playgroud)

更新

对于更新的示例

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"
Run Code Online (Sandbox Code Playgroud)