rdataframemergeoverwrite

How to overwrite/replace specific rows in R?


I have a dataset containing some data obtained after a correction that should be merged with the primary dataset. I need a way to overwrite the old values with the new ones, but I don't know how.

Here is an example of what I have:

Data <- data.frame(ID = c("Gfa","Gfa","Gfa","Pka","Pka","Pka"),
                Treatment = c("Control","T1","T2","Control","T1","T2"),
                Value = c(3,4,6,2,9,7))
                         
Data_new <- data.frame(ID = c("Gfa","Pka","Pka"),
                Treatment = c("Control","Control","T2"),
                Value = c(5,2,8))    

How can I merge the Data_new to the Data, overwriting only the new values?


Solution

  • library(dplyr)
    Data %>%
      rows_update(Data_new, by = c("ID", "Treatment"))
    
    
    Result
    
       ID Treatment Value
    1 Gfa   Control     5
    2 Gfa        T1     4
    3 Gfa        T2     6
    4 Pka   Control     2
    5 Pka        T1     9
    6 Pka        T2     8