[英]Counting rows in data.table that meet a condition
我有下表
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.
任何人都知道如何使最后一行工作?
刚刚怎么样
DT[.(3,5), .N]
# [1] 3
## These are also equivalent
## DT[J(3,5), .N]
## DT[list(3,5), .N]
这应该工作
DT[ y == 3 & v == 5, 计数 := .N]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.