简体   繁体   中英

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?

This works with duplicated :

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

$b
[1] 3

$c
[1] 4

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)

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

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM