Group pairs of matches into blocks of matching elements

  Kiến thức lập trình

So I have data.frame, with two columns of related indexes where every row refers to matching pair:

df <- data.frame(i=c(1,1,1,1,2,2,2,5), j=c(2,3,5,6,3,4,6,6))

|  i  |  j  |
-------------
|  1  |  2  |
|  1  |  3  |
|  1  |  5  |
|  1  |  6  |
|  2  |  3  |
|  2  |  4  |
|  2  |  6  |
|  5  |  6  |

And I would like to group these pairs into larger blocks, where every element matches every other element.

I managed to make a nested list where the i-th element is a list of indexes related to the i-th index, because I suppose I should make some kind of loop trough that list (I have 14 indexes in all):

1  :  2 3 4 5 6 8 9 10 12 13 14 
2  :  1 3 4 5 6 7 8 9 10 11 12 13 14 
3  :  1 2 4 6 8 9 10 11 12 13 14 
4  :  1 2 3 5 6 8 9 10 
5  :  1 2 4 
6  :  1 2 3 4 8 9 12 13 14 
7  :  2 9 12 
8  :  1 2 3 4 6 9 10 12 13 14 
9  :  1 2 3 4 6 7 8 10 12 13 
10  :  1 2 3 4 8 9 11 12 
11  :  2 3 10 
12  :  1 2 3 6 7 8 9 10 13 
13  :  1 2 3 6 8 9 12 14 
14  :  1 2 3 6 8 13 

However I have no idea what should I do next… I have also made a 0-1 14×14 matrix where 0 is lack of relation and 1 is relation so maybe that would be useful. I would like to get blocks like:

block1:  1,2,3
block2: 1,5,6
block3: 2,4
block4: 2,6   
... etc.

LEAVE A COMMENT