r - 按组查找向量中最频繁的组合

标签 r combinations

我有一个包含两列的表格,即 iditem :

df <- data.frame(id=c(1,1,2,2,2,2,3,3,3,4,4,4,4,4),item=c(1,2,3,1,2,3,4,1,2,3,1,2,1,2))

我想找到每个 id 3 个项目的最频繁组合(顺序无关紧要) .所以基本上,n选择 r哪里n = number of items within idr = 3 .每件元素数量id各不相同 - 有些超过 3,有些更少。

我是 R 新手并阅读了有关 combn 的信息和 expand.grid ,但我不知道如何在我的情况下使用它们(在每个 id 内工作)。

Find most frequent combination of values in a data.frame ”是我发现的最接近的问题。

编辑:基于示例的预期答案是组合“1,2,3”,它出现在 id 2 和 4 中。

最佳答案

这是使用 dplyr 的一个想法

df1 <- df %>% 
        group_by(id) %>% 
        arrange(item) %>% 
        summarise(new = paste(unique(combn(item, length(unique(item)), toString)), collapse = '/'))
df1
# A tibble: 4 × 2
#     id                                             new
#  <dbl>                                           <chr>
#1     1                                            1, 2
#2     2                     1, 2, 3 / 1, 3, 3 / 2, 3, 3
#3     3                                         1, 2, 4
#4     4 1, 1, 2 / 1, 1, 3 / 1, 2, 2 / 1, 2, 3 / 2, 2, 3

names(sort(table(unlist(strsplit(df1$new, '/'))), decreasing = TRUE)[1])
#[1] "1, 2, 3"

关于r - 按组查找向量中最频繁的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39748970/

相关文章:

python - 保留 Python 的 itertools.product 的顺序

r - 从 RDS 迁移到 Elastic MapReduce + Hive 是正确的选择吗?

algorithm - 生成所有可能的 split

r - 在两个其他引用类对象之间传递对引用类对象的引用(足球示例)

JSON解析错误,无效字符

Python Itertools Combinatinos 检索空列表

python - 来自 Pandas Dataframe 的 Fishers 精确测试

c++ - 对数字进行分组 C++

从ggplot2中删除某些图例变量和图例值?

r - 如何从 POSIXct 时间戳向量在 R 中创建日期部分?