2

I would like to extract an adjacency matrix of a giant component of a graph using R.

For example, I can create Erdos-Renyi g(n,p)

n = 100
p = 1.5/n
g = erdos.renyi.game(n, p)
coords = layout.fruchterman.reingold(g)
plot(g, layout=coords, vertex.size = 3, vertex.label=NA)

# Get the components of an undirected graph
cl = clusters(g)

# How many components?
cl$no           

# How big are these (the first row is size, the second is the number of components of that size)?
table(cl$csize) 

cl$membership
# Get the giant component
nodes = which(cl$membership == which.max(cl$csize))

# Color in red the nodes in the giant component and in sky blue the rest
V(g)$color  = "SkyBlue2"
V(g)[nodes]$color = "red"
plot(g, layout=coords, vertex.size = 3, vertex.label=NA)

here, I only want to extract the adjacency matrix of those red nodes.

enter image description here

1 Answers1

0

It's easy to get the giant component as a new graph like below and then get the adjacency matrix.

g  <- erdos.renyi.game(100, .015, directed = TRUE)
# if you have directed graph, decide if you want
# strongly or weakly connected components
co <- components(g, mode = 'STRONG')
gi <- induced.subgraph(g, which(co$membership == which.max(co$csize)))
# if you want here you can decide if you want values only
# in the upper or lower triangle or both
ad <- get.adjacency(gi)

But you might want to keep the vertex IDs of the original graph. In this case just subset the adjacency matrix:

g  <- erdos.renyi.game(100, .015)
co <- components(g)
gi_vids <- which(co$membership == which.max(co$csize))
gi_ad <- get.adjacency(g)[gi_vids, gi_vids]
# you can even add the names of the nodes
# as row and column names.
# generating dummy node names:
V(g)$name <- sapply(
    seq(vcount(g)),
    function(i){
        paste(letters[ceiling(runif(5) * 26)], collapse = '')
    }
)
rownames(gi_ad) <- V(g)$name[gi_vids]
colnames(gi_ad) <- V(g)$name[gi_vids]
deeenes
  • 4,148
  • 5
  • 43
  • 59