1
votes

I have an igraph object, which is basically a sparse matrix with both columns and rows labeled by id. I also have a data frame with row labels and a community value. I am trying to subset the adjacency matrix by selecting all rows and columns that match the row labels in the community data frame of some specific value.

I've tried various approaches with match, plyr, and subset, but cannot get anything to work. Below are two subsets of the data.

match(g2, communi)

>g2[1:3,1:3]
3 x 3 sparse Matrix of class "dgCMatrix"
        568120 711503 1077594
568120       .      7       4
711503       7      .       4
1077594      4      4       .

> head(communi)
        communi
568120        7
711503        7
1077594       7
1078147       7
772988      464
757866       72
1
Are you able to upload your matrix and data frame, or an example? - tospig
Sample data added. The communi data frame can easily be transformed into a list or other object, the igraph object not so much. - Mark C

1 Answers

2
votes

It's not clear if you want to subset the adjacency matrix or the graph, but here is an example of both.

# example graph from igraph documentation
library(igraph)   
g <- graph.full(5) %du% graph.full(5) %du% graph.full(5)
g <- add.edges(g, c(1,6, 1,11, 6, 11))

# calcualte community structure (many ways to do this)...
wtc <- walktrap.community(g)
# subset the graph (only community 1)
subgr <- induced.subgraph(g,membership(wtc)==1)
par(mfrow=c(1,2),mar=c(0,0,0,0))
plot(g)
plot(subgr)
# extract adjacency matrix from subgraph
get.adjacency(subgr)
# 5 x 5 sparse Matrix of class "dgCMatrix"
#               
# [1,] . 1 1 1 1
# [2,] 1 . 1 1 1
# [3,] 1 1 . 1 1
# [4,] 1 1 1 . 1
# [5,] 1 1 1 1 .

So in this example we subset the graph and then extract the adjacency matrix from that.