Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combine list elements based on element names

Tags:

r

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.

like image 468
Chargaff Avatar asked Sep 12 '13 14:09

Chargaff


People also ask

How do you combine list elements in python?

Using append() function One simple and popular way to merge(join) two lists in Python is using the in-built append() method of python. The append() method in python adds a single item to the existing list. It doesn't return a new list of items.

How do I combine lists in R?

R provided two inbuilt functions named c() and append() to combine two or more lists. c() function in R language accepts two or more lists as parameters and returns another list with the elements of both the lists.

Can you join lists with R?

Two or more R lists can be joined together. For that purpose, you can use the append , the c or the do. call functions. When combining the lists this way, the second list elements will be appended at the end of the first list.


2 Answers

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
like image 121
Ferdinand.kraft Avatar answered Oct 17 '22 11:10

Ferdinand.kraft


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.

like image 37
Giorgi Chighladze Avatar answered Oct 17 '22 10:10

Giorgi Chighladze