Tomas
Tomas

Reputation: 59475

Concatenate lists with override in R

How do I concatenate two lists in R in such a way that duplicate elements from the second one will override corresponding elements from the first one?

I tried c(), but it keeps duplicates:

l1 <- list(a = 1, b = 2)
l1 <- c(l1, list(b = 3, c = 4))

# $a
# [1] 1
# 
# $b
# [1] 2
# 
# $b
# [1] 3
#
# $c
# [1] 4

I want something that will produce this instead:

# $a
# [1] 1
# 
# $b
# [1] 3
#
# $c
# [1] 4

Hope that there exists something simpler than calling some *apply function?

Upvotes: 0

Views: 224

Answers (4)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

I suspect that you could get the behavior you want by using the "rlist" package; specifically, list.merge seems to do what you are looking for:

l1 <- list(a = 1, b = 2)
l2 <- list(b = 3, c = 4)
library(rlist)
list.merge(l1, l2)
# $a
# [1] 1
# 
# $b
# [1] 3
# 
# $c
# [1] 4 

Try list.merge(l2, l1) to get a sense of the function's behavior.


If you have just two lists, as noted by @PeterDee, the list.merge function pretty much makes modifyList accept more than two lists. Thus, for this particular example, you could skip loading any packages and directly do:

modifyList(l1, l2)

Upvotes: 4

martin
martin

Reputation: 63

I would suggest union:

l1 <- list(a = 1, b = 3)
l2 <- list(b = 3, c = 4)

union(l1, l2)

This works like a union in mathematics (Wiki link)

Upvotes: 0

dimitris_ps
dimitris_ps

Reputation: 5951

I am sure there is a quicker way than:

l1 <- list(a = 1, b = 2)
l2 <- list(b = 3, c = 4)

l1 <- c(l1[!(names(l1) %in% names(l2))],  l2)

You take the names of the l1 that are not in l2 and concatenate the two lists

Upvotes: 1

Peter Diakumis
Peter Diakumis

Reputation: 4042

This works with duplicated:

> l1[!duplicated(names(l1), fromLast=TRUE)]
$a
[1] 1

$b
[1] 3

$c
[1] 4

Upvotes: 5

Related Questions