Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find combinations of rows grouped by a column by picking 1 row from each group in dataframe

Tags:

r

combinations

I have a dataframe which can be grouped by column. Each row in a particular group has a unique id. By picking 1 row from each group, I want to form all possible combinations possible.

I have tried to solve it by combn() and expand.grid(). But was not able to get the desired solution.

I have following type of data

Col1  id  Unique id
A     1     A_1
A     2     A_2
B     1     B_1
C     1     C_1
C     2     C_2
C     3     C_3

I want something like this:

Groups or dataframes for following type:

(A_1,B_1,C_1)
(A_1,B_1,C_2)
(A_1,B_1,C_3)
(A_2,B_1,C_1)
(A_2,B_1,C_2)
(A_2,B_1,C_3)

Here I have shown only 3 groups that are A,B,C. I real dataset I can have any number of groups and each row can have any number of ids. Please help me for this with code or logic whatever possible.

like image 885
Priyesh Avatar asked Sep 12 '25 10:09

Priyesh


1 Answers

You can split unique_id by Col1 then use expand.grid().

expand.grid(split(df$Unique_id, f = df$Col1))

    A   B   C
1 A_1 B_1 C_1
2 A_2 B_1 C_1
3 A_1 B_1 C_2
4 A_2 B_1 C_2
5 A_1 B_1 C_3
6 A_2 B_1 C_3
like image 193
Ritchie Sacramento Avatar answered Sep 14 '25 00:09

Ritchie Sacramento