r - Filter data.table on multiple criteria in the same column -
i have next data.table
:
> dt= data.table(num=c(1,2,1,1,2, 3, 3,2), letters[1:8]) > dt num v2 1: 1 2: 1 c 3: 1 d 4: 2 b 5: 2 e 6: 2 h 7: 3 f 8: 3 g
i want filter num equals 1 , 2 , resulting data.table. can with:
> dt[num==1 | num==2,] num v2 1: 1 2: 1 c 3: 1 d 4: 2 b 5: 2 e 6: 2 h
or:
rbind(setkey(dt, num)[j(1)],setkey(dt, num)[j(2)])
but there alternative setkey sec look shorter like:
setkey(dt, num)[1|2]
since setkey code quicker big amount ... appreciate help!
in additions kfb's comment:
setkey(dt, num)[num %in% c(1,2)]
if filtering values integers in sequence:
setkey(dt,num)[j(1:2)] # or setkey(dt,num)[seq]
if arbitrary:
setkey(dt,num)[j(c(1,2)]
note 1: may not work in older versions of data.table
note 2: .
alias j
more readable:
setkey(dt,num)[.(1:2)]
fwiw, using magrittr
bundle data.table
, making clear possible:
dt %>% setkey(num) dt[ .(1:2) ]
the drawback can't neatly on 1 line.
r data.table
No comments:
Post a Comment