# R Programming/Network Analysis

## IntroductionEdit

We mainly use the following packages to demonstrate 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 igraphEdit

```
> # load the appropriate library
> library(igraph)
> # now create a few simple graphs
> # an undirected graph with 10 nodes and without any edge
> g1 <- graph.empty(10,directed=FALSE)
> # a directed graph with 10 nodes
> g2 <- graph.ring(10,directed=TRUE)
> # a complete undirected graph with 10 nodes
> g3 <- graph.full(10,directed=FALSE)
> # now get information about these graphs
> summary(g1)
> # g1 is an igraph object, U = Undirected, with 10 nodes and 0 edge
> IGRAPH U--- 10 0 --
> summary(g2)
> # g1 is an igraph object, D = Directed
> IGRAPH D--- 10 10 -- Ring graph
```

## Creating graphs from dataEdit

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 listEdit

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 plotting the graph from the edge list
gr <- graph.edgelist(el)
plot(gr)
```

### Creating graph from an adjacency matrixEdit

An adjacency matrix is a *n* × *n* matrix containing *n* vertices and where each entry *a _{ij}* 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)
```

## ReferencesEdit

- Statnet website includes all the documentation on network analysis using R.
- Julien Barnier's introduction (in French)
- Journal of Statistical Software #24 Special Issue on Networks in R