R: remove rows from one data frame that are in another

前端 未结 3 937
情书的邮戳
情书的邮戳 2021-02-08 21:32

I have two data frames df1 and df2. They have the same (two) columns. I want to remove the rows from df1 that are in df2.

3条回答
  •  被撕碎了的回忆
    2021-02-08 22:09

    Try this:

    df2 <-matrix(1:6,ncol=2,byrow=TRUE)
    df1 <-matrix(1:10,ncol=2,byrow=TRUE)
    
    data.frame(v1=setdiff(df1[,1], df2[,1]), v2=setdiff(df1[,2], df2[,2]))
      v1 v2
    1  7  8
    2  9 10
    

    Note that df1 and df2 are the same as Lapointe's but in the other way around, because you want to remove the rows from df1 that are in df2, so setdiff removes elements from x that are contained in y. See ?setdiff

    you'll get the same result as Lapointe's

提交回复
热议问题