R Programming/Network Analysis

From Wikibooks, open books for an open world
Jump to: navigation, search

Introduction[edit]

We mainly use following packages to demontrate network analysis in R: statnet, sna, igraph. They are however not representing a complete list. See Task view of gR, graphical models in R for a complete list.

Creating simple graphs with igraph[edit]

 
> # load the appropriate library
> library(igraph)
> # now create a few simple graphs
> g <- graph.empty(10,directed=FALSE)
> g2 <- graph.ring(10,directed=TRUE)
> g3 <- graph.full(10,directed=FALSE)
> # now get information about these graphs
> summary(g)

Creating graphs from data[edit]

First load the igraph package

library(igraph)

then you can choose your preferred format. Below are examples of data provided as edge list and as adjacency matrix.

Creating graph from an edge list[edit]

An edge list is formed by a two-column matrix, with each row defining one edge. An edge is drawn from each element in the first column to the corresponding element in the second one. Use the graph.edgelist() function to import your data.

 
# producing some random data in edge list form
el <- cbind(sample(1:10, 10), sample(1:10, 10))
 
# creating and plottig the graph from the edge list
gr <- graph.edgelist(el)
plot(gr)

Creating graph from an adjacency matrix[edit]

An adjacency matrix is a n × n matrix containing n vertices and where each entry aij represents the number of edges from vertex i to vertex j. To import your adjacency matrix, use the graph.adjacency() function.

 
# producing a random adjacency matrix
adj <- matrix(sample(0:1, 100, replace=T), 10, 10)
 
# creating and plottig the graph from the adjacency matrix
gr <- graph.adjacency(adj)
plot(gr)

References[edit]

Previous: Factor Analysis Index