Reputation: 794
I am trying to merge 2 lists in R. The names of the list should be used to perform the join. Here is a toy example:
> list1 <- list(A=c(1,2,3), B=c(2,4,5,6), C=c(1,3))
> list2 <- list(A=c(w,x), B=c(y,z))
The final merged list should look like this:
$w
[1] 1 2 3
$x
[1] 1 2 3
$y
[1] 2 4 5 6
$z
[1] 2 4 5 6
The only idea I had so far was to convert the lists to data frames, and use the merge function. Is there anything simpler to do?
Thanks a lot for your help.
Upvotes: 0
Views: 1357
Reputation: 2950
Hopefully this is something like what you want? In fact you don't need list2
at all. Because lists are actually vectors, we can use a named vector to "lookup" the values of list1
that we need, then assign those names to the new list
list1 <- list(A=c(1,2,3), B=c(2,4,5,6), C=c(1,3))
lookup <- c(w = "A",x = "A",y = "B",z = "B")
list2 <- list1[lookup]
names(list2) <- names(lookup)
list2
$w
[1] 1 2 3
$x
[1] 1 2 3
$y
[1] 2 4 5 6
$z
[1] 2 4 5 6
Upvotes: 5