How can I perform a “setdiff” merge using data.table?

后端 未结 2 537
暖寄归人
暖寄归人 2021-01-12 09:36

Say I have two tables:

library(data.table)
set.seed(1)

tab1 <- data.table(
  let = rep(letters[1:2], each = 3),
  num = rep(1:3, 2),
  val = rnorm(6),
           


        
2条回答
  •  清酒与你
    2021-01-12 10:25

    One solution would be to do a merge and remove the rows where there are values from tab2

    d<-as.data.frame(merge(tab1,tab2,all=T))
    t<-is.na(d[,4])
    d[t,][,-4]
    
     let num      val.x
    3   a   3 -0.8356286
    6   b   3 -0.8204684
    

    Using data.table :

    merge(tab1,tab2,all=T)[is.na(val.y), 1:3]
    
     let num      val.x
    1:   a   3 -0.8356286
    2:   b   3 -0.8204684
    

提交回复
热议问题