-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
_data-management.Rmd
137 lines (101 loc) · 2.17 KB
/
_data-management.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
---
title: "rank"
author: "George G. Vega Yon"
date: "May 4, 2018"
output: html_document
---
## R Markdown
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(igraph)
library(dplyr)
library(netplot)
set.seed(1231)
n <- 500
X <- cbind(school = sort(rep(1:5, n/5)))
net <- sample_smallworld(1, n, 4, .05)
nplot(net)
col <- viridis::viridis(5)
col <- col[X]
nplot(net, vertex.color = col)
# Adding X as an igraph attribute
V(net)$school <- X
```
Computing centrality measures
```{r}
V(net)$btw_cent <- betweenness(net, normalized = TRUE)
V(net)$ind_cent <- degree(net, mode="in")
```
Ranking
```{r}
dat <- igraph::as_data_frame(net, what = "vertices")
dat <- dplyr::as_tibble(dat)
dat$original_pos <- 1:nrow(dat)
dat <- group_by(dat, school)
dat <- arrange(
dat,
-ind_cent,
-btw_cent,
.by_group = TRUE
)
dat <- mutate(
dat,
school_size = length(original_pos),
pos = 1:school_size,
is_leader = as.integer(pos <= (school_size*0.05))
)
dat <- arrange(
dat,
original_pos
)
library(magrittr)
group_by(dat, school) %>%
arrange(
-ind_cent,
-btw_cent,
.by_group=TRUE) %>%
mutate(
pos = 1:school_size,
is_leader = as.integer(pos <= (school_size*.05) )
) %>%
arrange(original_pos) %>%
View
# In stata, group by: _N, this is equivalent to n() in dplyr
by(dat, dat$school, function(x) rank(x$ind_cent))
```
Taggin the leaders in igraph
```{r}
V(net)$is_leader <- dat$is_leader
```
Visualizing with netwplot
```{r}
is_leader_1_2 <- V(net)$is_leader + 1
nplot(
net,
vertex.size = c(1, 2)[is_leader_1_2],
vertex.size.range = c(.005, .05),
vertex.color = viridis::inferno(5)[V(net)$school],
bg.col = "black"
)
```
Example matching positions names in igraph
```{r}
# Creating a ring
x <- make_ring(5)
V(x)$name <- letters[1:5]
# Processing data
set.seed(123)
dat <- igraph::as_data_frame(x, what = "vertices")
dat$dummy <- runif(5) > .5
dat <- dat[order(runif(5)),,drop=FALSE] # Changed the sorting!
V(x)$name
# Getting the original position
ord <- match(
V(x)$name,
dat$name
)
dat <- dat[ord,,drop=FALSE]
V(x)$new_dummy <- dat$dummy
```