简体   繁体   English

R-合并列表的两个成员列表

[英]R - Merge Two member lists of a list

I have list l of the form say : 我有以下形式的清单l

R> l
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

Now, I want to merge to member lists of this list. 现在,我要合并到该列表的成员列表。 For instance, when I say I want to merge l[[1]] and l[[2]], I want the result to be : 例如,当我说我想合并l [[1]]和l [[2]]时,我希望结果是:

R> l
[[1]]
[1] 1 2

[[2]]
[1] 3

[[3]]
[1] 4

While merging two list, I don't need dupilcate elements in the result. 合并两个列表时,我不需要在结果中添加dupilcate元素。 Hence, I am using union over two member lists. 因此,我在两个成员列表上使用union

R> union(l[[1]], l,[[2]])
[1] 1 2

How can I do this merge operation? 我该如何进行合并操作? Can I do this using some predefined function? 我可以使用一些预定义的功能来做到这一点吗? Thanks 谢谢

You can write you own merge as follows: 您可以编写自己的合并,如下所示:

l <- as.list(1:4)

mymerge <- function(mylist, element1, element2){
  mylist[[element1]] <- union(mylist[[element1]], mylist[[element2]])
  mylist[[element2]] <- NULL
  return(mylist)
}

l <- mymerge(l,1,2)

Result: 结果:

> l
[[1]]
[1] 1 2

[[2]]
[1] 3

[[3]]
[1] 4

Comment: As akrun pointed out, you can also use c instead of union 注释:正如akrun指出的那样,您也可以使用c代替union

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM