[英]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.