9

How to combine this list of vectors by elements names ?

L1 <- list(F01=c(1,2,3,4),F02=c(10,20,30),F01=c(5,6,7,8,9),F02=c(40,50))

So to get :

results <- list(F01=c(1,2,3,4,5,6,7,8),F02=c(10,20,30,40,50))

I tried to apply the following solution merge lists by elements names but I can't figure out how to adapt this to my situation.

Community
  • 1
  • 1
Chargaff
  • 1,562
  • 2
  • 19
  • 41

2 Answers2

9
sapply(unique(names(L1)), function(x) unname(unlist(L1[names(L1)==x])), simplify=FALSE)
$F01
[1] 1 2 3 4 5 6 7 8 9

$F02
[1] 10 20 30 40 50
Ferdinand.kraft
  • 12,579
  • 10
  • 47
  • 69
  • 1
    Great, your a life saver. What's the purpose of unname here, if I may ask ? Thank you. – Chargaff Sep 12 '13 at 15:08
  • @Chargaff, without `unname`, each vector has a name attribute, inherited from the list element name. Try it and you'll see it. Also, it's better to add `simplify=FALSE` above, to avoid gettin a matrix instead of a list. I'm editing the answer now. – Ferdinand.kraft Sep 12 '13 at 15:10
  • 1
    Instead of `unname` you could add the option `use.names = F` in `unlist`. But both methods remove the original names of the vector... – durum Dec 22 '15 at 13:52
1

You can achieve the same result using map function from purrr

map(unique(names(L1)), ~ flatten_dbl(L1[names(L1) == .x])) %>%
  set_names(unique(names(L1)))

The first line transforms the data by merging elements with matching names, while the last line renames new list accordingly.