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.
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
(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.
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
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