Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Most Frequent Combination within a Vector by Group

Tags:

r

combinations

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))

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.

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.

EDIT: The expected answer based on the example is the combination "1, 2, 3", which appears in id 2 and 4.

like image 369
DGenchev Avatar asked Sep 28 '16 13:09

DGenchev


1 Answers

Here is one idea using 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"
like image 69
Sotos Avatar answered Nov 16 '22 16:11

Sotos