---
title: "A dolphin social network"
output: html_document
---
```{r setup, include=FALSE}
# cache results
knitr::opts_chunk$set(cache=TRUE, fig.align='center')
```
David Lusseau, a researcher at the University of Aberdeen, observed the group of dolphins of Doubtful Sound. Every time a school of dolphins was encountered in the fjord between 1995 and 2001, each adult member of the school was photographed and identified from natural markings on the dorsal fin. This information was utilised to determine how often two individuals were seen together. Read the
[full story](https://medium.com/@cento_otto/a-social-network-of-dolphins-c073f3b8502d).
## Dataset
* A [CSV](dolphin_nodes.csv) with names and sex of dolphins
* A [CSV](dolphin_edges.csv) with ties among dolphins
## Data challenges
1. Is the network assortative by sex?
1. Is the network assortative by node degree?
## Analysis
```{r library, message=FALSE, warning=FALSE}
library(tidyverse)
library(igraph)
```
### Read dataset
```{r read}
edges = read_csv("dolphin_edges.csv")
nodes = read_csv("dolphin_nodes.csv")
nodes = mutate(nodes, id = row_number()) %>% select(id, everything())
g = graph_from_data_frame(edges, directed = FALSE, vertices = nodes)
```
### Assortativity by sex
```{r, eval=TRUE, echo=TRUE}
# males and females
male = V(g)$sex == "M"
names(male) = V(g)$name
# absolute modularity
modularity(g, membership = male + 1)
# relative modularity
edge = as_edgelist(g)
l = c(edge[,1], edge[,2])
r = c(edge[,2], edge[,1])
sexl = male[l]
sexr = male[r]
cor(sexl, sexr)
```
### Assortativity by degree
```{r}
d = degree(g)
edge = as_edgelist(g)
l = c(edge[,1], edge[,2])
r = c(edge[,2], edge[,1])
dl = d[l]
dr = d[r]
cor(dl, dr)
```