按组查找向量中的最频繁组合 [英] Find Most Frequent Combination within a Vector by Group

查看:45
本文介绍了按组查找向量中的最频繁组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两列的表,分别为 id item

I have a table with two columns namely id and item:

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 。因此,基本上, n 选择 r ,其中 n = id中的项目数 r = 3 。每个 id 的项目数量各不相同-有些超过3,有些更少。

I want to find the most frequent combination (order doesn't matter) of 3 items per id. So basically, n choose r where n = number of items within id and r = 3. The number of items per id varies - some have more than 3, some have less.

我是新来的R并阅读有关 combn expand.grid 的信息,但我不知道如何在我的情况下使用它们(可以在每个 id 中使用)。

I am new to R and read about combn and expand.grid, but I don't know how to use them in my case (to work within each id).

在数据帧中查找最频繁的值组合。是我发现的最接近的问题。

"Find most frequent combination of values in a data.frame" is the closest question I found.

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

The expected answer based on the example is the combination "1, 2, 3", which appears in id 2 and 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"

这篇关于按组查找向量中的最频繁组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆