Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Overwrite list values from another list [duplicate]

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?

like image 500
Fredrik Karlsson Avatar asked Dec 09 '25 08:12

Fredrik Karlsson


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
like image 160
Ronak Shah Avatar answered Dec 10 '25 22:12

Ronak Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!