计算 data.table 中满足条件的行数
Counting rows in data.table that meet a condition
我有以下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.
有人知道如何使最后一行起作用吗?
怎么样
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, count := .N]
我有以下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.
有人知道如何使最后一行起作用吗?
怎么样
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, count := .N]