How can I skip groups while subsetting with key by in data.table?

帅比萌擦擦* 提交于 2019-12-11 14:06:17

问题


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?



来源:https://stackoverflow.com/questions/36869784/how-can-i-skip-groups-while-subsetting-with-key-by-in-data-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!