[英]R data.table intersection of all groups
我希望擁有數據表的所有組的交集。 所以對於給定的數據:
data.table(a=c(1,2,3, 2, 3,2), myGroup=c("x","x","x", "y", "z","z"))
我希望得到結果:
2
我知道
Reduce(intersect, list(c(1,2,3), c(2), c(3,2)))
將給出我想要的結果,但我沒有弄清楚如何生成data.table查詢組的列表。
我會嘗試以下列方式使用Reduce
(假設dt
是您的數據)
Reduce(intersect, dt[, .(list(unique(a))), myGroup]$V1)
## [1] 2
這是一種方法。
nGroups <- length(unique(dt[,myGroup]))
dt[, if(length(unique(myGroup))==nGroups) .BY else NULL, by="a"][[1]]
# [1] 2
這里有一些解釋性的評論。
## Mark down the number of groups in your data set
nGroups <- length(unique(dt[,myGroup]))
## Then, use `by="a"` to examine in turn subsets formed by each value of "a".
## For subsets having the full complement of groups
## (i.e. those for which `length(unique(myGroup))==nGroups)`,
## return the value of "a" (stored in .BY).
## For the other subsets, return NULL.
dt[, if(length(unique(myGroup))==nGroups) .BY else NULL, by="a"][[1]]
# [1] 2
如果該代碼和評論本身不明確,快速瀏覽以下內容可能會有所幫助。 基本上,上面的方法只是尋找和報告的值a
為那些返回基團x,y,z
在柱V1
以下。
dt[,list(list(unique(myGroup))), by="a"]
# a V1
# 1: 1 x
# 2: 2 x,y,z
# 3: 3 x,z
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.