# Chapter 2 - Manipulating Network Data

``````library(igraph)
library(mosaic)``````

### Undirected graph

``````g <- graph.formula(1-2, 1-3, 2-3, 2-4, 3-5, 4-5, 4-6, 4-7, 5-6, 6-7)
V(g)``````
``````## + 7/7 vertices, named, from 3d6e147:
## [1] 1 2 3 4 5 6 7``````
``E(g)``
``````## + 10/10 edges from 3d6e147 (vertex names):
##  [1] 1--2 1--3 2--3 2--4 3--5 4--5 4--6 4--7 5--6 6--7``````
``print_all(g)  #str() is defunct``
``````## IGRAPH 3d6e147 UN-- 7 10 --
## + attr: name (v/c)
## + edges (vertex names):
## 1 -- 2, 3
## 2 -- 1, 3, 4
## 3 -- 1, 2, 5
## 4 -- 2, 5, 6, 7
## 5 -- 3, 4, 6
## 6 -- 4, 5, 7
## 7 -- 4, 6``````
``plot(g)``

### Directed graph/digraph

``````dg <- graph.formula(1-+2, 1-+3, 2++3, 4-+1, 2++4)
plot(dg)``````

### Change vertex labels

``````V(dg)\$name <- c("Shirley", "Jenny", "Cici", "Zhiling")
plot(dg)``````

### Representations for Graphs

There are 3 basic formats for representing a graph: adjacency lists, edge lists, and adjacency matrices.

``print_all(dg)``
``````## IGRAPH ca24ec8 DN-- 4 7 --
## + attr: name (v/c)
## + edges from ca24ec8 (vertex names):
## [1] Shirley->Jenny   Shirley->Cici    Jenny  ->Cici    Jenny  ->Zhiling
## [5] Cici   ->Jenny   Zhiling->Shirley Zhiling->Jenny``````
``get.edgelist(dg)``
``````##      [,1]      [,2]
## [1,] "Shirley" "Jenny"
## [2,] "Shirley" "Cici"
## [3,] "Jenny"   "Cici"
## [4,] "Jenny"   "Zhiling"
## [5,] "Cici"    "Jenny"
## [6,] "Zhiling" "Shirley"
## [7,] "Zhiling" "Jenny"``````
``get.adjacency(dg)``
``````## 4 x 4 sparse Matrix of class "dgCMatrix"
##         Shirley Jenny Cici Zhiling
## Shirley       .     1    1       .
## Jenny         .     .    1       1
## Cici          .     1    .       .
## Zhiling       1     1    .       .``````
``get.adjacency(g)``
``````## 7 x 7 sparse Matrix of class "dgCMatrix"
##   1 2 3 4 5 6 7
## 1 . 1 1 . . . .
## 2 1 . 1 1 . . .
## 3 1 1 . . 1 . .
## 4 . 1 . . 1 1 1
## 5 . . 1 1 . 1 .
## 6 . . . 1 1 . 1
## 7 . . . 1 . 1 .``````

### Operations on graphs

``````h1 <- induced.subgraph(g, 1:5)
print_all(h1)``````
``````## IGRAPH 7210b39 UN-- 5 6 --
## + attr: name (v/c)
## + edges from 7210b39 (vertex names):
## [1] 1--2 1--3 2--3 2--4 3--5 4--5``````
``get.edgelist(h1)``
``````##      [,1] [,2]
## [1,] "1"  "2"
## [2,] "1"  "3"
## [3,] "2"  "3"
## [4,] "2"  "4"
## [5,] "3"  "5"
## [6,] "4"  "5"``````
``plot(h1)``