I have two lists with named elements:
a <- list(a=1, b=2) b <- list(b=3, c=4)
I want to combine these lists, so that any elements in a that have the same names will be overwritten by the list b, so I get this out:
list(a=1, b=3, c=4)
I know I could do this in a loop, but is there a more compact way of doing this in R?
combine. lists(list1, list2) returns a list consisting in the elements found in either list1 or list2, giving precedence to values found in list2 for dimensions found in both lists. Two lists to be combined.
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.
R has a built in function to do that modifyList
modifyList(a, b)
Here's a simple solution:
# create new list newlist <- c(a,b) # remove list element(s) newlist[!duplicated(names(newlist), fromLast = TRUE)]
The result:
$a [1] 1 $b [1] 3 $c [1] 4
An even simpler solution with setdiff
:
c(a[setdiff(names(a), names(b))], b) $a [1] 1 $b [1] 3 $c [1] 4
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