Potato_head
Potato_head

Reputation: 356

R - Merge Two member lists of a list

I have list l of the form say :

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 :

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. Hence, I am using union over two member lists.

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

Upvotes: 1

Views: 80

Answers (1)

Rentrop
Rentrop

Reputation: 21497

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

Upvotes: 2

Related Questions