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.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With