forked from core-methods-in-edm/assignment3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Assignment 3.Rmd
232 lines (158 loc) · 9.3 KB
/
Assignment 3.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# Assignment 3 - Social Network Analysis
## Part I
Start by installing the "igraph" package. Once you have installed igraph, load the package.
Now upload the data file "comment-data.csv" as a data frame called "D1". Each row represents a comment from one student to another so the first line shows that student "28" commented on the comment of student "21". It also shows the gender of both students and the students' main elective field of study ("major"").
```{r}
D1 <- read.csv("comment-data.csv", header = TRUE)
```
Before you proceed, you will need to change the data type of the student id variable. Since it is a number R will automatically think it is an integer and code it as such (look at the list of variables by clicking on the data frame arrow in the Data pane. Here you will see the letters "int"" next to the stid variable, that stands for integer). However, in this case we are treating the variable as a category, there is no numeric meaning in the variable. So we need to change the format to be a category, what R calls a "factor". We can do this with the following code:
```{r}
D1$comment.to <- as.factor(D1$comment.to)
D1$comment.from <- as.factor(D1$comment.from)
```
igraph requires data to be in a particular structure. There are several structures that it can use but we will be using a combination of an "edge list" and a "vertex list" in this assignment. As you might imagine the edge list contains a list of all the relationships between students and any characteristics of those edges that we might be interested in. There are two essential variables in the edge list a "from" variable and a "to" variable that descibe the relationships between vertices. While the vertex list contains all the characteristics of those vertices, in our case gender and major.
So let's convert our data into an edge list!
First we will isolate the variables that are of interest: comment.from and comment.to
```{r}
library(dplyr)
D2 <- select(D1, comment.to, comment.from) #select() chooses the columns
```
Since our data represnts every time a student makes a comment there are multiple rows when the same student comments more than once on another student's video. We want to collapse these into a single row, with a variable that shows how many times a student-student pair appears.
```{r}
EDGE <- count(D2, comment.to, comment.from)
names(EDGE) <- c("from", "to", "count")
```
EDGE is your edge list. Now we need to make the vertex list, a list of all the students and their characteristics in our network. Because there are some students who only recieve comments and do not give any we will need to combine the comment.from and comment.to variables to produce a complete list.
```{r}
#First we will separate the commenters from our commentees
V.FROM <- select(D1, comment.from, from.gender, from.major)
#Now we will separate the commentees from our commenters
V.TO <- select(D1, comment.to, to.gender, to.major)
#Make sure that the from and to data frames have the same variables names
names(V.FROM) <- c("id", "gender.from", "major.from")
names(V.TO) <- c("id", "gender.to", "major.to")
#Make sure that the id variable in both dataframes has the same number of levels
lvls <- sort(union(levels(V.FROM$id), levels(V.TO$id)))
VERTEX <- full_join(mutate(V.FROM, id=factor(id, levels=lvls)),
mutate(V.TO, id=factor(id, levels=lvls)), by = "id")
#Fill in missing gender and major values - ifelse() will convert factors to numerical values so convert to character
VERTEX$gender.from <- ifelse(is.na(VERTEX$gender.from) == TRUE, as.factor(as.character(VERTEX$gender.to)), as.factor(as.character(VERTEX$gender.from)))
VERTEX$major.from <- ifelse(is.na(VERTEX$major.from) == TRUE, as.factor(as.character(VERTEX$major.to)), as.factor(as.character(VERTEX$major.from)))
#Remove redundant gender and major variables
VERTEX <- select(VERTEX, id, gender.from, major.from)
#rename variables
names(VERTEX) <- c("id", "gender", "major")
#Remove all the repeats so that we just have a list of each student and their characteristics
VERTEX <- unique(VERTEX)
```
Now we have both a Vertex and Edge list it is time to plot our graph!
```{r}
#Load the igraph package
library(igraph)
#First we will make an object that contains the graph information using our two dataframes EDGE and VERTEX. Notice that we have made "directed = TRUE" - our graph is directed since comments are being given from one student to another.
g <- graph.data.frame(EDGE, directed=TRUE, vertices=VERTEX)
#Now we can plot our graph using the force directed graphing technique - our old friend Fruchertman-Reingold!
plot(g,layout=layout.fruchterman.reingold)
#There are many ways to change the attributes of the graph to represent different characteristics of the newtork. For example, we can color the nodes according to gender.
plot(g,layout=layout.fruchterman.reingold, vertex.color=VERTEX$gender)
#We can change the thickness of the edge according to the number of times a particular student has sent another student a comment.
plot(g,layout=layout.fruchterman.reingold, vertex.color=VERTEX$gender, edge.width=EDGE$count)
````
## Part II
In Part II your task is to [look up](http://igraph.org/r/) in the igraph documentation and modify the graph above so that:
* Ensure that sizing allows for an unobstructed view of the network features (For example, the arrow size is smaller)
* The vertices are colored according to major
* The vertices are sized according to the number of comments they have recieved
```{r}
C1<- data.frame(table(D1$comment.to))
names(C1)= c("id", "comment.to1")
C2 <- data.frame(VERTEX$id,rep(0, times=length(VERTEX$id)))
names(C2) = c("id","comment.to2")
Comment.to.size<- left_join(C2,C1)
Comment.to.size$comment.to1<- ifelse(is.na(Comment.to.size$comment.to1)==TRUE,0,Comment.to.size$comment.to1)
Comment.to.size$comment.to = Comment.to.size$comment.to1 + Comment.to.size$comment.to2
Csize = select(Comment.to.size, id, comment.to)
plot( g,layout=layout.fruchterman.reingold, vertex.color=VERTEX$major,vertex.size=Csize$comment.to+10, edge.width=EDGE$count,edge.arrow.size=.2)
```
## Part III
Now practice with data from our class. This data is real class data directly exported from Qualtrics and you will need to wrangle it into shape before you can work with it. Import it into R as a data frame and look at it carefully to identify problems.
```{r}
library(tidyr)
library(dplyr)
library(stringr)
library(igraph)
```
Please create a **person-network** with the data set hudk4050-classes.csv. To create this network you will need to create a person-class matrix using the tidyr functions and then create a person-person matrix using `t()`. You will then need to plot a matrix rather than a to/from data frame using igraph.
Once you have done this, also [look up](http://igraph.org/r/) how to generate the following network metrics:
* Betweeness centrality and dregree centrality. **Who is the most central person in the network according to these two metrics? Write a sentence or two that describes your interpretation of these metrics**
* Color the nodes according to interest. Are there any clusters of interest that correspond to clusters in the network? Write a sentence or two describing your interpetation.
### To Submit Your Assignment
Please submit your assignment by first "knitting" your RMarkdown document into an html file and then comit, push and pull request both the RMarkdown file and the html file.
```{r}
# Input data
C1 <- read.csv("hudk4050-classes.csv", stringsAsFactors = FALSE, header = TRUE)
# Copy to play with data
C2 <- C1
#Data Tidying
#Make header first row
colnames(C2) <- C2[1,]
#Remove unwanted rows
C2 <- slice(C2, 3:49)
#Remove last column
C2 <- select(C2, 1:8)
#Merge name columns
C2 <- unite(C2, "name", 'First Name', 'Last Name', sep = " ")
#Remove unpredictable characters from names
C2$name <- str_replace(C2$name, "`", "")
#Make all names capitalized first letters only
C2$name <- str_to_title(C2$name)
#Make all class letters capitals
C2 <- C2 %>% mutate_at(2:7, list(toupper))
#Remove whitespace between letters and numbers in class
C2 <- C2 %>% mutate_at(2:7, str_replace_all, " ", "")
```
#Data restructuring
```{r}
#Create a dataframe with two variable, student and class
C3 <- C2 %>% gather(label, class, 2:7, na.rm = TRUE, convert = FALSE) %>% select(name, class)
#Create a new variable containing 1s that will become our counts
C3$count <- 1
#Remove blank classes
C3 <- filter(C3, class != "")
#Remove deplicates (Danny!)
C3 <- unique(C3)
#Spread 1s across classes to create a student x class dataframe
C3<- spread(C3, class, count)
#Make row names student names
rownames(C3) <- C3$name
#Remove names column AND HUDK4050
C3 <- select(C3, -name, -HUDK4050)
#Shortest:
C3[is.na(C3)] <- 0
#Cheat way:
C3 <- ifelse(is.na(C3),0,1)
```
#Matrix operations
```{r}
#Convert to matrix
C4 <- as.matrix(C3)
#Create p-p matrix
C4 <- C4 %*% t(C4)
```
#Graphing
```{r}
g <- graph.adjacency(C4, mode="undirected", diag = FALSE)
plot(g, layout=layout.fruchterman.reingold,
vertex.size=4,
#degree(g)*0.7
vertex.label.cex =0.8,
vertex.label.color="black",
vertex.color="gainsboro")
```
#Centrality
```{r}
#Calculate the degree centrality of the nodes, showing who has the most connections
sort(degree(g), decreasing = TRUE)
#Calculate the betweeness centrality, showing how many "shortest paths" pass through each nodes
sort(betweenness(g), decreasing = TRUE)
```