Search code examples
rneural-networkigraphgraph-theoryadjacency-matrix

Mapping affiliations to adjacency matrix output


Let's say I'm using this affiliation matrix:

library(igraph)

A=c(1,1,0,0) 
B=c(1,0,1,0) 
C=c(1,0,1,0) 
D=c(0,1,0,1) 
E=c(0,0,1,1) 
aff=matrix(c(A,B,C,D,E),nrow=5,byrow=TRUE) 
dimnames(aff)=list(c("A","B","C","D","E"),c("Group1","Group2","Group3","Group4"))

Which looks like this:

##   Group1 Group2 Group3 Group4
## A      1      1      0      0
## B      1      0      1      0
## C      1      0      1      0
## D      0      1      0      1
## E      0      0      1      1

From which you can produce (using aff %*% t(aff)) the following adjacency matrix:

##   A B C D E
## A 2 1 1 1 0
## B 1 2 2 0 1
## C 1 2 2 0 1
## D 1 0 0 2 1
## E 0 1 1 1 2

The groups (e.g. Group1, Group2, etc.) are not preserved in the transformation to an adjacency matrix, thus when plotting:

m2=aff %*% t(aff)
g2=graph_from_adjacency_matrix(m2, "undirected", weighted=T, diag=F)
plot(g2, edge.width=E(g2)$weight)

enter image description here

There is no way to know what shared group connection exists between A and B, A and C, etc.

My question: Is there some way to preserve this grouping variable so that the plot could be made from the adjacency matrix while allowing the edges to be labelled as Group3 or Group1 like so?:

enter image description here

Note: I'm planning to use visNetwork, not igraph, but this question seems to stem from the data structure itself rather than the package used, so I've chosen this for simplicity's sake.


Solution

  • m3 = get.edgelist(g2)
    lbls = sapply(1:NROW(m3), function(i){
        toString(names(which(aff[m3[i, 1],] == 1 & aff[m3[i, 2],] == 1)))
    })
    plot(g2, edge.label = lbls)