我如何 select table 的所有行与另一个 table 中的行相匹配

how can I select all rows of a table that match those in another table

我想用 data.table 做一些非常简单的事情,但我失去了惯用的方法

library(data.table)
set.seed(1)
DT = data.table(a=sample(letters,1e5,T), b=sample(letters,1e5,T), c=rnorm(1e5))
DT2 = data.table(a=sample(letters,5,T), b=sample(letters,5,T)) 

DT2
   a b
1: k h
2: e v
3: f n
4: m q
5: w v

我想要 select DT 的行与 DT2 的行相匹配。 因此,操作后的行数将始终小于初始 table.

我想要这样的东西:

> DT[paste(a,b) %chin% DT2[,paste(a,b)]]
     a b          c
  1: m q -0.4974579
  2: e v -0.1325602
  3: w v -1.8081050
  4: m q  0.9025120
  5: w v -0.4958802
 ---               
729: f n  0.5604650
730: f n -1.2607321
731: m q  0.5146013
732: m q -1.8329656
733: k h -0.9752011
> DT2[paste(a,b) %chin% DT[,paste(a,b)]]
   a b
1: e v
2: f n
3: k h
4: m q
5: w v
> 

内部联接应该做:

setkey(DT, a, b)[DT2, nomatch=0]

产生:

     a b          c
  1: k h -1.6592442
  2: k h  1.1946471
  3: k h -0.8694933
  4: k h  0.7789158
  5: k h -1.3142607
 ---               
729: w v -0.3516787
730: w v  0.5272145
731: w v -0.7531717
732: w v  0.3352228
733: w v  0.1182353

如果您想知道 DT2 中的哪些值存在于 DT 中,那么:

unique(setkey(DT[, .(a, b)], a, b))[DT2, nomatch=0]