---
# System prepended metadata

title: Network analysis with tidygraph
tags: [bym4102]

---

---
title: "Network analysis with tidygraph"
tags: bym4102
author: "alper yilmaz"
date: "6/3/2021"
output: html_document
---

# Network analysis with tidygraph

simple friend or following network

```{r}
friends <- tibble::tribble(
       ~person1, ~person2,
        "alice",    "bob",
      "charles",    "bob",
        "david",    "bob",
          "bob",  "allen",
        "fiona",    "bob",
         "gary",    "bob",
          "bob",  "henry",
        "alice",  "allen",
        "david",  "fiona"
      )

friends
```

let's convert this dataframe to a graph/network

```{r}
library(tidygraph)

friends_g <- friends %>% as_tbl_graph()

friends_g
```

Notice that `friends_g` is "A directed acyclic simple graph with 1 component"

Let's calculate degrees. Notice that "bob" is followed by 5 people, "bob" follows 2 people (total degree 7)

```{r}
friends_g %>% mutate(deg = centrality_degree())
```
The default degree is `mode="out"`

We can get all degrees

```{r}
friends_g %>% 
  mutate(deg = centrality_degree(mode="all"))
```

Or only incoming connections

```{r}
friends_g %>% 
  mutate(deg = centrality_degree(mode="in"))
```

Let's prepare an undirected graph

```{r}
friends_ug <- friends %>% as_tbl_graph(directed = FALSE)

friends_ug
```
In this new network let's check degrees


```{r}
friends_ug %>% 
  mutate(deg=centrality_degree())
```

```{r}
friends_ug %>% 
  mutate(deg=centrality_degree(mode="all"))
```
> So, in undirected graph mode does not matter



## Visualization

Let's use this graph for visualization

![](https://miro.medium.com/max/1389/1*3c8vydsK4zzs4roaox7SZQ.jpeg)


```{r}
sample_net <- readxl::read_excel("data/sample_network.xlsx") %>% 
  as_tbl_graph(directed=FALSE)

sample_net
```
```{r}
sample_net %>% 
  mutate(deg=centrality_degree())
```
We can use ggraph packgage for network visualization

```{r}
library(ggraph)
sample_net %>% 
  ggraph() +
  geom_node_point() +
  geom_edge_link()
  
```

```{r}
sample_net %>% 
  ggraph() +
  geom_node_point() +
  geom_edge_link() +
  geom_node_label(aes(label=name)) +
  theme_graph()
```

```{r}
sample_net %>% 
  ggraph() +
  geom_node_point(aes(size=centrality_degree())) +
  geom_edge_link() +
  geom_node_label(aes(label=name),repel = T) +
  theme_graph()
```
```{r}
sample_net %>%
  ggraph() +
  geom_node_point(aes(size=centrality_betweenness())) +  # filter=centrality_degree() > 2
  geom_edge_link() +
  geom_node_label(aes(label=name),repel = T) +
  theme_graph()
```
```{r}
sample_net %>%
  ggraph() +
  geom_node_point(aes(size=centrality_degree(), color=centrality_eigen())) +  
  geom_edge_link() +
  geom_node_label(aes(label=name),repel = T) +
  theme_graph()
```

