Search code examples
rdatetimedplyrrbind

I want to rbind 2 rows but without overlapping rows in R


I have data1 and data2.

data1 <- data.frame(date = c(123, 124, 125, 126),
                    peter = c(10, 11, NA, NA),
                    turner = c(20, 21, NA, NA))

data2 <- data.frame(date = c(124, 125, 126, 127, 128),
                    peter = c(12, 10, 30, 50, 70),
                    turner = c(23, 20, 40, 60, 80))

My goal is to rbind data1 and data2. However, as you can see, date overlaps .I have to make sure that when I bind them, date has to be not overlapped. So, I want to use the non-overlapping rows from data1 and use the other rows from data2 and rbind them together. In this example, date=124,125,126 overlaps. So,my desired output should look like this:

data=data.frame(date=c(123,124,125,126,127,128), peter=c(10,12,10,30,50,70), turner=c(20,23,20,40,60,80))

I don't know how to do in R.


Solution

  • Sounds like you want dplyr::rows_upsert() which adds new rows or overwrites existing rows by key:

    library(dplyr)
    
    rows_upsert(data1, data2, by = "date")
    
      date peter turner
    1  123    10     20
    2  124    12     23
    3  125    10     20
    4  126    30     40
    5  127    50     60
    6  128    70     80