Home > Software design >  Merge list elements of one single list by name in R
Merge list elements of one single list by name in R

Time:10-10

I have one list with a large number of elements (supposed to be an inverse index in the end).

  • All elements are numeric vectors with a different length.
  • The name of an element occurs multiple times
> par.list
$NAMEA
[1]  1  2  3  4  5  7  8  9 10

$NAMEB
[1] 6

$NAMEB
[1] 11 12 13 16 17

$NAMEA
[1] 14 15 18 19 20

What I look for is an efficient was such that I get

> merged.list
$NAMEA
[1]  1  2  3  4  5  7  8  9 10 14 15 18 19 20

$NAMEB
[1] 6 11 12 13 16 17

I am sure that there is an easy way to do it but I just don't happen to find the right thread here, so I would appreciate any help!

CodePudding user response:

We may stack the named list to a two column data.frame and split

with(stack(par.list), split(values, ind))

-output

$NAMEA
 [1]  1  2  3  4  5  7  8  9 10 14 15 18 19 20

$NAMEB
[1]  6 11 12 13 16 17

data

par.list <- list(NAMEA = c(1, 2, 3, 4, 5, 7, 8, 9, 10), NAMEB = 6, NAMEB = c(11L, 
12L, 13L, 16L, 17L), NAMEA = c(14L, 15L, 18L, 19L, 20L))
  • Related