How to count occurrences combinations in data.table in R

痞子三分冷 提交于 2019-11-29 02:36:21

You just need to add by=list(a,b).

DT1[,count_combination_in_dt2:=nrow(DT2[J(a,b),nomatch=0]), by=list(a,b)]
DT1
## 
##    a b count_combination_in_dt2
## 1: 3 8                        3
## 2: 2 3                        1

EDIT: Some more details: In your original version, you used DT2[DT1, nomatch=0] (because you used all a, b combinations. If you want to use J(a,b) for each a, b combination separately, you need to use the by argument. The data.table is then grouped by a, b and the nrow(...) is evaluated within each group.

setkey(DT2, w, x)

DT2[DT1, .N, by = .EACHI]
#   w x N
#1: 3 8 3
#2: 2 3 1

# In versions <= 1.9.2, use DT2[DT1, .N] instead

The above simply does the merge and counts the number of rows for each group defined by the i-expression, thus by = .EACHI.

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