R数据表:所有组的交集

6

我希望能够获取数据表中所有组的交集。假设有以下数据:

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查询可以得到我想要的结果,但我不知道如何生成数据表查询结果中组的列表。

2个回答

7

我建议您可以尝试以下方式使用Reduce(假设dt是您的数据)

Reduce(intersect, dt[, .(list(unique(a))), myGroup]$V1)
## [1] 2

1
我喜欢它。它更简单,更易于理解,而且肯定更符合OP所使用的方法。 - Josh O'Brien

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

如果这段代码和注释本身并不清晰,那么快速浏览以下内容可能会有所帮助。基本上,上面的方法只是查找并报告在下面的V1列中返回x,y,z的组的a值。请保留HTML标签。
dt[,list(list(unique(myGroup))), by="a"]
#    a    V1
# 1: 1     x
# 2: 2 x,y,z
# 3: 3   x,z

@BondedDust -- 好的,添加了一些解释。 - Josh O'Brien

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接