Search code examples
rdataframedelete-row

Delete all rows below specific row in R matching another value on a different data frame


I want to delete all rows in df1 below a specific row. This specific row always matches the first value ("Name") with df2.

df1: | Name | Shape| Date | |:--------|------|------| | 00000 | row |10-2020| | 00001 | row |11-2020| |00002 |row |12-2020| |00003 |row |13-2020| |00004 |row |14-2020|

df2: | Name | Shape| Date | |:-------- | -----|------| |00002 |row |12-2020| |00003 |row |13-2020| |00004 |row |14-2020|

enter image description here

In this case all rows on df1 below 0002 would be deleted. On df2 rows below 00002 don't necessarily match rows below 00002 on df1. Thanks.


Solution

  • Here is one way to get df1 with rows below the first entry of df2$Name removed via the which function (I just entered "datechar" rather than each date you have in your example since the date is not used).

    df1 <- data.frame("Name"=seq(0,4),
                      "Shape"=rep("row",5),
                      "Date"=rep("datechar",5))
                      
    df2 <- data.frame("Name"=seq(2,4),
                      "Shape"=rep("row",3),
                      "Date"=rep("datechar",3))
    
    which(df1$Name == df2$Name[1])
    
    df1[1:(which(df1$Name == df2$Name[1])),]