forked from core-methods-in-edm/assignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Assignment2_JUNG.Rmd
248 lines (156 loc) · 9.93 KB
/
Assignment2_JUNG.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# Assignment 2 - Social Network Analysis
## Part I
Start by installing the "igraph" package. Once you have installed igraph, load the package.
```{r}
## Download and install the package
#install.packages("igraph")
## Load package
library(igraph)
```
Now upload the data file "discipline-data.csv" as a data frame called "D1". Each row is a disciplinary action from a teacher to a student so the first line shows that teacher "E" sent student "21" to the principal. It also shows the gender of both the teacher and student and the student's main elective field of study ("major"") and the field that the teacher instructs in ("t.expertise").
```{r}
D1 <- read.csv("discipline-data.csv")
```
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$stid <- as.factor(D1$stid)
```
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". As you might imagine the edge list contains a list of all the relationships between students and teachers 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 (a disciplinary action is given "from" and teacher "to" a student). 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: tid and stid
```{r}
library(dplyr)
D2 <- select(D1, tid, stid)
```
Since our data represnts every time a teacher sends a student to the principal there are multiple rows when the same teacher sends the same student. We want to collapse these into a single row, with a variable that shows how many times a teacher-student pair appears.
```{r}
EDGE <- count(D2, tid, stid)
names(EDGE) <- c("from", "to", "count")
```
EDGE is your edge list. Now we need to make the vertex list, a list of all the teachers and students and their characteristics in our network.
```{r}
#First we will separate the teachers from our original data frame
V.TCH <- select(D1, tid, t.gender, t.expertise)
#Remove all the repeats so that we just have a list of each teacher and their characteristics
V.TCH <- unique(V.TCH)
#Add a variable that describes that they are teachers
V.TCH$group <- "teacher"
#Now repeat this process for the students
V.STD <- select(D1, stid, s.gender, s.major)
V.STD <- unique(V.STD)
V.STD$group <- "student"
#Make sure that the student and teacher data frames have the same variables names
names(V.TCH) <- c("id", "gender", "topic", "group")
names(V.STD) <- c("id", "gender", "topic", "group")
#Bind the two data frames together (you will get a warning because the teacher data frame has 5 types of id (A,B,C,D,E) and the student has 25 (1-30), this isn't a problem)
VERTEX <- bind_rows(V.TCH, V.STD)
```
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 discipline is being given from a teacher to a student.
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 teacher has sent a particular student to the principal.
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 create a graph that sizes the student vertices in terms of the number of disciplinary actions they have recieved, and the teachers in terms of the number of disciplinary actions they have given out.
```{r}
library(dplyr)
#EDGE
#How many disciplinary actions that the teachers have given
disCountTeacher <- aggregate(EDGE$count, by=list (Category = EDGE$from), FUN = sum)
#How many disciplinary actions that the students have received
disCountStudent <- aggregate(EDGE$count, by=list (Category = EDGE$to), FUN = sum)
#VERTEX
#Teacher Vertex
V.TCH2 <- arrange(V.TCH, id)
V.TCH2$disCountTeacher <- disCountTeacher$x
#Student Vertex
V.STD2 <- arrange(V.STD, id)
V.STD2$disCountStudent <- disCountStudent$x
#Make sure that the student and teacher data frames have the same variables names
names(V.TCH2) <- c("id", "gender", "topic", "group","disCount")
names(V.STD2) <- c("id", "gender", "topic", "group","disCount")
#Bind the two data frames together (you will get a warning because the teacher data frame has 5 types of id (A,B,C,D,E) and the student has 25 (1-30), this isn't a problem)
VERTEX2 <- bind_rows(V.TCH2, V.STD2)
#graph
g2 <- graph.data.frame(EDGE, directed=TRUE, vertices=VERTEX2)
#plot the graph
plot(g2,layout=layout.fruchterman.reingold, vertex.size=VERTEX2$disCount)
#plot the graph - nodes with different colors for different genders & edge width according to the number of disciplines that teacher has given out
plot(g2,layout=layout.fruchterman.reingold, vertex.size=VERTEX2$disCount, vertex.color=VERTEX$gender, edge.width=EDGE$count)
```
```
## Part III
Now practice with data from our class. 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 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. **Who is the most central person in the network?**
```{r}
#import data
library(readr)
Classes<- read_csv("~/EdDataMiningR/Assignment2/Assignment2_JUNG/hudk4050-classes.csv")
Classes <- Classes[-c(1,2), ]
##-----Person-Class Matrix-----##
#create a dataframe that contains listed variables
personClass <- data.frame(Classes$Q8, Classes$Q1, Classes$Q3, Classes$Q4, Classes$Q5 )
#gather classes columns into rows
library(tidyr)
personClass <- gather(personClass, classNumber, classNames, Classes.Q1:Classes.Q5)
#get rid of all the spaces to reduce irrecularities
personClass[] <- lapply(personClass, function(x) as.character(gsub(" ", "", x)))
#rename the columns
names(personClass) <- c("studentNames", "classNumbers","classNames")
#remove the classNumber columns and all the NA values
personClass <- subset(personClass, select = c("studentNames","classNames"))
personClass <- na.omit(personClass)
#remove all the HUDK4050 (class that all of us are taking) for simplicity
personClass <- filter(personClass, classNames != "HUDK4050")
#add a column with count
countPC <- count(personClass, studentNames, classNames)
names(countPC) <- c("studentNames", "classNames", "count")
#spread
countPCdf<- spread(countPC, classNames, count)
#convert it to matrix
countPCMat <-data.matrix(countPCdf, rownames.force = NA)
rownames(countPCMat) <- c(countPCdf$studentNames)
countPCMat[is.na(countPCMat)] <- 0
personClassMat <- countPCMat[,-c(1) ]
##-----Person-Person Matrix-----##
#transpose countPCMat into countCPMat
classPersonMat <- t(personClassMat)
#create person-person matrix by multiplying person-class and class-person matrices
personPersonMat <- personClassMat %*% classPersonMat
#diagnonals of person-person matrix gives no meaningful info (how many classes each person takes - no relation to other students) therefore, remove all the diagnonals
diag(personPersonMat)<-NA
##-----betweeness centrality-----##
library(igraph)
library(dplyr)
#plot network graph
g3 <- graph.adjacency(personPersonMat,mode="undirected")
plot.igraph(g3,layout=layout.fruchterman.reingold, vertex.size=10,vertex.label.cex=0.3)
#betweenness centrality
#vertex betweenness
btwness <- betweenness(g3)
btwness <- as.data.frame(btwness)
vertexBtwness <- tibble::rownames_to_column(btwness, "studentNames")
##-----**Who is the most central person in the network?**-----##
centralPerson <- subset(btwness, btwness==max(btwness))
#the person with highest betweenness value is Lintong.
#edge betweenness
edgeBtwness <- edge_betweenness(g3, e = E(g3), directed = FALSE, weights = NULL)
edgeBtwness <- as.data.frame(edgeBtwness)
##-----betweeness degree-----##
#degree centrality: "counts the number of links held by each node and points at individuals who can quickly connect with the wider network... local measure since it does not take into account the rest of the network and the importance you give to its value depends strongly on the network's size"
degreeCent <- centr_degree(g3,mode="all")
degreeCentdf <- as.data.frame(degreeCent$res)
degreeCentdf <- cbind(degreeCentdf, vertexBtwness$studentNames)
names(degreeCentdf) <- c("degree", "studentNames")
highDegreePerson <- subset(degreeCentdf, degree==max(degree))
```
### 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.