Joakim Lundborg
Joakim Lundborg

Reputation: 11200

Combine lists while overriding values with same name in R

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?

Upvotes: 33

Views: 10569

Answers (2)

Ramnath
Ramnath

Reputation: 55695

R has a built in function to do that modifyList

modifyList(a, b)

Upvotes: 64

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

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

Upvotes: 8

Related Questions