Tuesday, May 13, 2014

Create network with igraph in 4 simple steps

Lets say, we have a data-frame with node-node-edge values as following,


Now we will build a network based on this data.

Step 1: Load the data and do basic validity checks.


 # Clear the workspace   
 rm(list=ls())
  
 # Load the data  
 load("nData.rda")  

 # Do basic checks to ensure the validity of the data   
 dim(nData)  
 head(nData)  
 tail(nData)  

Step 2: Create network data frame

 # Select edges with significant association only  
 data <- nData[which(nData[,3] < 0.005),]  

 # Perform check on new data frame  
 dim(data)  
 head(data)  
 tail(data)  

 # Create network (graph) data frame  
 network.data <- graph.data.frame(data,directed=F)  

Step 3 Load the package

 # Install igraph if not already installed  
 install.packages("igraph")  

 # Load the package  
 library(igraph)  

Step 4: Check the data and plot the network

 # Print vertices  
 V(network.data)  

 # Print edges  
 E(network.data) 
 
 # Plot the network  
 plot(network.data)  


In our case it looks like set of disjoint graphs, like following.


Optional steps


We can also refine network based of the degree centrality. Lets try to remove vertices with degree centrality less than three.

 # Identify vertices to remove  
 data.to.remove <- V(network.data)[ degree(network.data) < 3 ]  

 # Remove vertices from data  
 network.data <- delete.vertices(network.data, data.to.remove)  

We can add more details in network by choosing different color for different type of vertices.

 # Color vertices associated with Arizona state in red, remaining in white.  
 V(network.data)$color <- ifelse(V(network.data)$state == 'AZ','red','white')  


No comments:

Post a Comment