How can I skip groups while subsetting with key by

2019-07-25 05:12发布

问题:

I have this DT:

dt=data.table(ID=c(rep(letters[1:2],each=4),'b'),value=seq(1,9))
   ID value
1:  a     1
2:  a     2
3:  a     3
4:  a     4
5:  b     5
6:  b     6
7:  b     7
8:  b     8
9:  b     9

I need to eliminate groups while subsetting but only when the data fulfils some condition. Something like this does not work:

dt[,{if (.N==4) .SD else NULL
     v1},by="ID"]

So that I need to remove the groups that do not meet the condition. In this example I would like to skip the groups which length is different than 4. So that I get:

   ID value
1:  a     1
2:  a     2
3:  a     3
4:  a     4

But I haven't been able to work this around, I would appreciate any help.

回答1:

@jangorecki came up with the answer:

does dt[, if (.N==4) .SD, by="ID"] answer your question?