Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine lists while overriding values with same name in R

Tags:

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?

like image 514
Joakim Lundborg Avatar asked Jan 22 '13 09:01

Joakim Lundborg


People also ask

How do I put two lists together 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.

How do I combine list elements in R?

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.


2 Answers

R has a built in function to do that modifyList

modifyList(a, b) 
like image 51
Ramnath Avatar answered Sep 20 '22 07:09

Ramnath


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 
like image 40
Sven Hohenstein Avatar answered Sep 21 '22 07:09

Sven Hohenstein