Search code examples
rgraphigraphpairwise

Building sets from pairwise comparisons


Trying to formulate my problem generically: I did a pairwise comparison of multiple elements and want to build sets (groups) from this adjacency matrix (i.e. build groups where of elements where the pairwise comparison equals TRUE).

For example: I have 6 shapes. Shape 1 overlaps shape 2, which overlaps shape 3. Shape 4 is alone, shape 5 overlaps shape 6 (see below)

enter image description here

If i do a pairwise comparison between all shapes and ask if they overlap another shape, I receive this following matrix.

(Please note: This is the starting point of my question. The image above and the story about shapes just serves as an example)

      [,1]  [,2]  [,3]  [,4]  [,5]  [,6]
[1,]  TRUE  TRUE FALSE FALSE FALSE FALSE # shape 1 overlaps shapes 1 and 2
[2,]  TRUE  TRUE  TRUE FALSE FALSE FALSE # shape 2 overlaps shapes 1, 2 and 3
[3,] FALSE  TRUE  TRUE FALSE FALSE FALSE # etc...
[4,] FALSE FALSE FALSE  TRUE FALSE FALSE
[5,] FALSE FALSE FALSE FALSE  TRUE  TRUE
[6,] FALSE FALSE FALSE FALSE  TRUE  TRUE

I'm looking for a method with which I can build the following groups (group order does not matter):

  • Group a: shapes 1, 2 and 3
  • Group b: shape 4
  • Group c: shapes 5 and 6

You can use the following code to reproduce the pairwise comparison matrix:

adjacency_matrix <- matrix(c(TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE),nrow = 6) 

Solution

  • I wrote the question after having found the solution myself. Hope this helps anybody stuggling to solve this problem without finding the right words to formulate it.

    Turns out, this is very simple problem in the domain of graph theory. You can use igraph to turn the adjacency matrix into a graph and then to determine it's components:

    library(igraph)
    
    mygraph <- graph_from_adjacency_matrix(adjacency_matrix)
    
    mycomponents <- components(mygraph) # you can vary between "weak" and "strong", depending on your context
    
    mycomponents$membership # the memberships in the order as they appear in the matrix
    
    [1] 1 1 1 2 3 3
    
    plot(mygraph)
    

    enter image description here