Navin Manaswi
Navin Manaswi

Reputation: 992

Creating groups based on connectedness

A network is given.

nodes <- data.frame( id = 1:8, label = paste0("Node", 1:8))
edges <- data.frame(from = from, to = to)
library(visNetwork ) # you can use anyone of igraph, rneo4j as well
visNetwork(nodes, edges)

enter image description here

As we are looking for connected networks, we got 2 connected networks(CN) here. First CN : (1,2,5,6,7) and Second CN : (3,4,8)

we attach a group_id to each CN. So each node of the first CN has group_id 1 and that of second CN, group_id 2.

Final aim is to create a column of group_id by using some algorithms.

In the above case, by observing the image

 group_id <- c(1,1,2,2,1,1,1,2)
 modified_nodes <- cbind(nodes,group_id)

Upvotes: -1

Views: 432

Answers (1)

Stibu
Stibu

Reputation: 15907

I'm not familiar with visNetwork, but it seems to be focused on visualisation rather than analysis of graphs. Thus, I propose an igraph solution.

The igraph object can be directly created from your data frame edges and plotted with plot():

library(igraph)
from <- c(8, 4, 1, 2, 5, 5)
to <- c(4, 3, 2, 5, 6, 7)
edges <- data.frame(from = from, to = to)
g <- graph_from_data_frame(edges, directed = FALSE)
plot(g)

enter image description here

igraph offers many functions to analyze a graph. You can get the various disconnected components of the graph with components():

components(g)
## $membership
## 8 4 1 2 5 3 6 7 
## 1 1 2 2 2 1 2 2 
## 
## $csize
## [1] 3 5
## 
## $no
## [1] 2

$membership is exactly what you asked for. So this would give you a data frame of all the vertices with the number of the component they belong to:

memb <- components(g)$membership
nodes <- data.frame(id = names(memb),
                    group_id = memb)
nodes <- nodes[order(nodes$id), ]
nodes
##   id group_id
## 1  1        2
## 2  2        2
## 3  3        1
## 4  4        1
## 5  5        2
## 6  6        2
## 7  7        2
## 8  8        1

Alternatively, you could add the column group_id to your data frame nodes:

nodes <- data.frame( id = 1:8, label = paste0("Node", 1:8))
nodes$group_id <- components(g)$membership[as.character(nodes$id)]

Note that you need to convert nodes$id to character to make sure that you actually index with names.

Upvotes: 1

Related Questions