I have two lists, whose elements have partially overlapping names, which I need to merge/combine together into a single list, element by element:
> lst1 <- list(integers=c(1:7), letters=letters[1:5], words=c("two", "strings")) > lst2 <- list(letters=letters[1:10], booleans=c(TRUE, TRUE, FALSE, TRUE), words=c("another", "two"), floats=c(1.2, 2.4, 3.8, 5.6)) > lst1 $integers [1] 1 2 3 4 5 6 7 $letters [1] "a" "b" "c" "d" "e" $words [1] "two" "strings" > lst2 $letters [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" $booleans [1] TRUE TRUE FALSE TRUE $words [1] "another" "two" $floats [1] 1.2 2.4 3.8 5.6
I tried using mapply, which basically combines the two lists by index (i.e.: "[["), while I need to combine them by name (i.e.: "$"). In addition, since the lists have different lengths, the recycling rule is applied (with rather unpredictable results).
> mapply(c, lst1, lst2) $integers [1] "1" "2" "3" "4" "5" "6" "7" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" $letters [1] "a" "b" "c" "d" "e" "TRUE" "TRUE" "FALSE" "TRUE" $words [1] "two" "strings" "another" "two" $<NA> [1] 1.0 2.0 3.0 4.0 5.0 6.0 7.0 1.2 2.4 3.8 5.6 Warning message: In mapply(c, lst1, lst2) : longer argument not a multiple of length of shorter
As you might imagine, what I'm looking for is:
$integers [1] 1 2 3 4 5 6 7 $letters [1] "a" "b" "c" "d" "e" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" $words [1] "two" "strings" "another" "two" $booleans [1] TRUE TRUE FALSE TRUE $floats [1] 1.2 2.4 3.8 5.6
Is there any way to achieve that? Thank you!
Join / Merge two lists in python using + operator In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.
Using append() 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, instead, it modifies the original list by adding the item to the end of the list.
Combine lists in 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.
You can do:
keys <- unique(c(names(lst1), names(lst2))) setNames(mapply(c, lst1[keys], lst2[keys]), keys)
Generalization to any number of lists would require a mix of do.call
and lapply
:
l <- list(lst1, lst2, lst1) keys <- unique(unlist(lapply(l, names))) setNames(do.call(mapply, c(FUN=c, lapply(l, `[`, keys))), keys)
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