计算满足条件的data.table中的行

时间:2015-01-22 11:32:12

标签: r count data.table

我有下表

DT = data.table(x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=rep(4:6, 3))

我想计算满足条件的行数(y==3 & v==5)。

我可以获得满足条件的行,因此我可以保存它们然后计算行数。但是,我知道.N可以更有效地完成它,我只是不知道如何。我的代码:

require(data.table)
keycols = c("y","v")
setkeyv(DT,keycols) 

DT[J(3,5)] # This gets the subset I am interested in

DT[ , `:=` (count = .N), by = J(3,5)] # This is one of the multiple unsuccessful ways I have been trying to count the rows. 

任何人都知道如何使最后一行工作?

2 个答案:

答案 0 :(得分:6)

如何

DT[.(3,5), .N]
# [1] 3

## These are also equivalent
## DT[J(3,5), .N]
## DT[list(3,5), .N]

答案 1 :(得分:0)

这应该有效

DT [y == 3&v == 5,计数:= .N]