R Overwrite list values from another list

Viewed 404

I need to merge two lists so that the values of the second list overwrites the corresponding list item in the first if there are duplicates. Is there a way to do this without using a slow for loop in R?

A simple example:

A <- list("First"=1,"Second"=2)
B <- list("First"=3,"Third"=3)
C <- A
for(curr in names(B)){ C[curr] <- B[curr] }

and the content of C is now

> C
$First
[1] 3

$Second
[1] 2

$Third
[1] 3

what is what I want. But, could this be done without the for loop?

1 Answers

You can use names of B to change value in C.

C[names(B)] <- B
C

#$First
#[1] 3

#$Second
#[1] 2

#$Third
#[1] 3
Related