# Going viral with R’s igraph package

March 23, 2014
By

(This article was first published on quantitate, and kindly contributed to R-bloggers)

R's igraph package provides a simple and flexible set of utilities for working with graphs.  In this post, we'll use this package to animate the simulated spread of a disease through a network.

# Graphs

A graph is just a collection of nodes joined by edges:
require(igraph)# Specify an undirected graph by hand, using a numeric   # vector of the pairs of vertices sharing an edge.G <- graph( c(1,2,1,3,1,4,3,4,3,5,5,6,6,7,7,8,8,9,3,8,5,8), directed = FALSE )# visualization  plot(G, layout = layout.fruchterman.reingold,       vertex.size = 25,       vertex.color="red",       vertex.frame.color= "white",       vertex.label.color = "white",       vertex.label.family = "sans",       edge.width=2,         edge.color="black")

In graph models, the nodes of a graph typically represent entities and the edges represent relationships between these entities. Both nodes and edges may have attributes or qualities that characterize the entities and the relationships. A node might have an attribute of "color". An edge might have an attribute of "weight" that encodes the strength of the relationship between the vertices that the edge joins. The igraph package makes it very simple to manage the assignment of attributes to the components of a graph:
require(igraph)G <- graph( c(1,2,1,3,1,4,3,4,3,5,5,6,6,7,7,8,8,9,3,8,5,8), directed = FALSE )# Assign attributes to the graphG$name <- "A colorful example graph"# Assign attributes to the graph's verticesV(G)$name  <- toupper(letters[1:9])V(G)$color <- sample(rainbow(9),9,replace=FALSE)# Assign attributes to the edgesE(G)$weight <- runif(length(E(G)),.5,4)# Plot the graph -- details in the "Drawing graphs" section of the igraph manualplot(G, layout = layout.fruchterman.reingold,      main = G$name, vertex.label = V(G)$name,     vertex.size = 25,     vertex.color= V(G)$color, vertex.frame.color= "white", vertex.label.color = "white", vertex.label.family = "sans", edge.width=E(G)$weight,      edge.color="black")

# Building a simulation

The ease and flexibility with which you can assign and update attributes of a graph's nodes and edges makes igraph a powerful tool for prototyping simulations with graphs. Let's consider a very simplified example. Let $G$ be a graph whose nodes are people in a population. Two nodes in $G$ will share an edge if they have daily in-person contact with each other. Suppose also that a virus has infected a few nodes of $G$. These infected nodes can spread the virus to other uninfected nodes with whom they have daily contact. Newly infected nodes will then spread the virus to other nodes, and so on. Let's use the simple probability model: $$p(x \mbox{ infects } y | x \mbox{ is infected}, y \mbox{ is uninfected}, x\mbox{ and } y \mbox{ share an edge})= \frac{1}{2}.$$
Here is a function that implements this simulation model: