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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With