【发布时间】:2019-07-25 10:15:14
【问题描述】:
我们有一个数据框,其中一列用于类别,一列用于离散值。我们希望获取所有类别组合的所有可能交集(公共值的数量)。
我想出了以下代码。但是,那里有更短的东西吗?我确信有一种更好的方法可以做到这一点,一个专门的功能可以做到这一点。当然,下面的代码可以缩短,例如使用purrr:map,但这不是我的问题。
## prepare an example data set
df <- data.frame(category=rep(LETTERS[1:5], each=20),
value=sample(letters[1:10], 100, replace=T))
cats <- unique(df$category)
n <- length(cats)
## all combinations of 1...n unique elements from category
combinations <- lapply(1:n, function(i) combn(cats, i, simplify=FALSE))
combinations <- unlist(combinations, recursive=FALSE)
names(combinations) <- sapply(combinations, paste0, collapse="")
## for each combination of categories, get the values which belong
## to this category
intersections <- lapply(combinations,
function(co)
lapply(co, function(.x) df$value[ df$category == .x ]))
intersections <- lapply(intersections,
function(.x) Reduce(intersect, .x))
intersections <- sapply(intersections, length)
这给我们带来了我想要的结果:
> intersections
A B C D E AB AC AD AE BC
20 20 20 20 20 10 8 8 9 8
BD BE CD CE DE ABC ABD ABE ACD ACE
8 9 7 8 8 8 8 9 7 8
ADE BCD BCE BDE CDE ABCD ABCE ABDE ACDE BCDE
8 7 8 8 7 7 8 8 7 7
ABCDE
7
问题:有没有办法以更少的模糊度达到相同的结果?
【问题讨论】:
标签: r set intersection