Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the complement of a subset of a data table?

Tags:

r

data.table

set.seed(77)
dt<-data.table(a=seq(1,5))
> dt
   a
1: 1
2: 2
3: 3
4: 4
5: 5

dtsub<-dt[sample(5,3)]
> dtsub
   a
1: 2
2: 3
3: 4

How do I get the complement of dtsub (i.e. the rows in dt which are not in dtsub)? Please generalize the solution to work for any data table.

Note: I'm sure this has been asked before, but my google searches came up empty. If this is a duplicate, please mark it as so and point me in the right direction.

like image 904
Ben Avatar asked Dec 07 '25 17:12

Ben


1 Answers

library(data.table)
set.seed(77)
dt<-data.table(a=seq(1,5))
dtsub<-dt[sample(5,3)]

setkey(dt,a)
setkey(dtsub,a)

dt[!dtsub]
#   a
#1: 1
#2: 5
like image 95
Roland Avatar answered Dec 09 '25 15:12

Roland