0

I need to create a subgraph from an adjacency matrix selecting by affiliation data. How do I match an adjacency and an affiliation matrix?

Take the following adjacency matrix:

    A   B   C   D   E   F   G
A   0   1   0   1   0   1   0
B   1   0   1   1   0   1   0
C   0   1   0   0   0   0   0
D   1   1   0   0   1   1   0
E   0   0   0   1   0   1   0
F   1   1   0   1   1   0   1
G   0   0   0   0   0   1   0

And the following affiliation matrix:

    P   R   Q
A   1   1   0
B   1   0   1
C   1   1   0
D   0   1   0
E   1   0   1
F   0   0   1
G   1   1   0

How do I create a subgraph from the adjacency matrix only with the nodes corresponding to P in the affiliation matrix?

NBK
  • 887
  • 9
  • 20

1 Answers1

1

If your goal is to:

  • filter out nodes from your adjacency matrix where the corresponding P is 1 in the affiliation matrix
  • convert filtered adjacency matrix to an igraph object

then you can accomplish that with the following:

# the names(which()) isn't needed for the subset of adj
p_nodes <- names(which(aff[,"P"] == 1))
p_adj   <- adj[p_nodes, p_nodes]

p_graph <- igraph::graph.adjacency(p_graph)
Adam Spannbauer
  • 2,707
  • 1
  • 17
  • 27
  • Adam, these codes work for the small test matrices in the original question, but not for my large, real matrices of 867 nodes. The error I'm getting is "Error in adj[P_nodes, P_nodes] : subscript out of bounds". You know what may be the problem? The large matrices work perfectly fine on their own, but haven't been able to combine them. – NBK May 30 '17 at 19:59
  • you get that error when you reference an index that doesnt exist (i.e. `x <- matrix(1:4, nrow=2); colnames(x) <- c("a","b"); x[,"c"]` or `matrix(1:4, nrow=2)[3,3]`. double check that whatever the definition of `P_nodes` is makes sense in the context of `adj` – Adam Spannbauer May 31 '17 at 00:09
  • Hi Adam, thanks for the response. I changed the names of the nodes to "name1", "name2",... "name867", but left the matrices otherwise untouched -- and the codes now work. This means that the problem was not the inexistence of the index. Any clue what the problem may be? Cheers. – NBK May 31 '17 at 11:25
  • glad you got it working. you can see this [SO discussion](https://stackoverflow.com/questions/15031338/subscript-out-of-bounds-general-definition-and-solution) if you want to follow up more on your error, but without your data it would be hard to make a guess as to what caused the error in your case – Adam Spannbauer May 31 '17 at 12:16