From 51d8fe9451adff66c30eebfd6c0b7f4e2e41996a Mon Sep 17 00:00:00 2001 From: louiserr98 Date: Wed, 21 Oct 2020 10:52:34 +0800 Subject: [PATCH] assignment3 --- Assignment 3.Rmd | 58 ++++- Assignment-3.html | 639 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 695 insertions(+), 2 deletions(-) create mode 100644 Assignment-3.html diff --git a/Assignment 3.Rmd b/Assignment 3.Rmd index 649407e..881914f 100644 --- a/Assignment 3.Rmd +++ b/Assignment 3.Rmd @@ -34,7 +34,7 @@ Since our data represnts every time a student makes a comment there are multiple EDGE <- count(D2, comment.to, comment.from) -names(EDGE) <- c("from", "to", "count") +names(EDGE) <- c("to", "from", "count") ``` @@ -96,7 +96,7 @@ plot(g,layout=layout.fruchterman.reingold, vertex.color=VERTEX$gender) plot(g,layout=layout.fruchterman.reingold, vertex.color=VERTEX$gender, edge.width=EDGE$count) -```` +``` ## Part II @@ -104,6 +104,18 @@ In Part II your task is to [look up](http://igraph.org/r/) in the igraph documen * 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 + +```{r} + +Num <- count(D2, comment.to) +names(Num) <- c("id", "count") +Num <- left_join(VERTEX,Num,by=c("id")) +Num$count[is.na(Num$count)] <- 0 + +plot(g,layout=layout.fruchterman.reingold, edge.arrow.size=0.5,vertex.color=VERTEX$major, edge.width=EDGE$count, vertex.size=15+Num$count ) + +``` + * The vertices are sized according to the number of comments they have recieved ## Part III @@ -112,10 +124,52 @@ Now practice with data from our class. This data is real class data directly exp 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. +```{r} +library(stringr) +library(tidyr) + +#TidyData +PN <- read.csv("hudk4050-classes.csv",stringsAsFactors = FALSE, header = TRUE) +names(PN) = c("FirstName","LastName","Class1","Class2","Class3","Class4","Class5","Class6","Interest") +PN$Name = paste(PN$FirstName,PN$LastName) +PN <- select(PN,1:7) + + +PN <- PN %>% mutate_at(2:7,list(toupper)) +PN <- PN %>% mutate_at(2:7,str_replace_all," ","") +PN <- tidyr::unite(PN, "Name", FirstName, LastName, remove=TRUE) + +PN1 <- PN %>% gather(label, Class, 2:6, na.rm = TRUE, convert = FALSE ) %>% select(Name,Class) + +PN1$Count <- 1 +PN1 <- filter(PN1, Class != "") +PN1 <- unique(PN1) +PN1 <- spread(PN1,Class,Count) +rownames(PN1) <- PN1$Name +PN1 <- select(PN1,-Name,-HUDK4050) +PN1[is.na(PN1)]<- 0 + +PC <- as.matrix(PN1) + +PP <- PC %*% t(PC) + +``` + +```{r} +PPlot <- graph.adjacency(PP, mode="undirected", diag = FALSE) +plot(PPlot, layout=layout.fruchterman.reingold,vertex.size=4,vertex.label.cex=0.5,vertex.label.color="red",vertex.color="gainsboro") +``` + + 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** +```{r} +sort(degree(PPlot),decreasing=TRUE) +sort(betweenness(PPlot),decreasing=TRUE) +``` + * 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 diff --git a/Assignment-3.html b/Assignment-3.html new file mode 100644 index 0000000..4f413cb --- /dev/null +++ b/Assignment-3.html @@ -0,0 +1,639 @@ + + + + + + + + + + + + + +Assignment-3.utf8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + +
+

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”").

+
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:

+
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

+
library(dplyr)
+
## 
+## Attaching package: 'dplyr'
+
## The following objects are masked from 'package:stats':
+## 
+##     filter, lag
+
## The following objects are masked from 'package:base':
+## 
+##     intersect, setdiff, setequal, union
+
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.

+
EDGE <- count(D2, comment.to, comment.from)
+
+names(EDGE) <- c("to", "from", "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.

+
#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!

+
#Load the igraph package
+
+library(igraph)
+
## 
+## Attaching package: 'igraph'
+
## The following objects are masked from 'package:dplyr':
+## 
+##     as_data_frame, groups, union
+
## The following objects are masked from 'package:stats':
+## 
+##     decompose, spectrum
+
## The following object is masked from 'package:base':
+## 
+##     union
+
#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 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
  • +
+
Num <- count(D2, comment.to)
+names(Num) <- c("id", "count")
+Num <- left_join(VERTEX,Num,by=c("id"))
+Num$count[is.na(Num$count)] <- 0
+
+plot(g,layout=layout.fruchterman.reingold, edge.arrow.size=0.5,vertex.color=VERTEX$major, edge.width=EDGE$count, vertex.size=15+Num$count )
+

+
    +
  • The vertices are sized according to the number of comments they have recieved
  • +
+
+
+

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.

+

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.

+
library(stringr)
+library(tidyr)
+
## 
+## Attaching package: 'tidyr'
+
## The following object is masked from 'package:igraph':
+## 
+##     crossing
+
#TidyData
+PN <- read.csv("hudk4050-classes.csv",stringsAsFactors = FALSE, header = TRUE)
+names(PN) = c("FirstName","LastName","Class1","Class2","Class3","Class4","Class5","Class6","Interest")
+PN$Name = paste(PN$FirstName,PN$LastName)
+PN <- select(PN,1:7)
+
+
+PN <- PN %>% mutate_at(2:7,list(toupper))
+PN <- PN %>% mutate_at(2:7,str_replace_all," ","")
+PN <- tidyr::unite(PN, "Name", FirstName, LastName, remove=TRUE)
+
+PN1 <- PN %>% gather(label, Class, 2:6, na.rm = TRUE, convert = FALSE ) %>% select(Name,Class)
+
+PN1$Count <- 1
+PN1 <- filter(PN1, Class != "")
+PN1 <- unique(PN1)
+PN1 <- spread(PN1,Class,Count)
+rownames(PN1) <- PN1$Name
+PN1 <- select(PN1,-Name,-HUDK4050)
+PN1[is.na(PN1)]<- 0
+
+PC <- as.matrix(PN1)
+
+PP <- PC %*% t(PC)
+
PPlot <- graph.adjacency(PP, mode="undirected", diag = FALSE)
+plot(PPlot, layout=layout.fruchterman.reingold,vertex.size=4,vertex.label.cex=0.5,vertex.label.color="red",vertex.color="gainsboro")
+

+

Once you have done this, also look up 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
  • +
+
sort(degree(PPlot),decreasing=TRUE)
+
##          Guoliang_XU          Hangshi_JIN           Jiaao `_QI 
+##                   31                   31                   31 
+##          Jiacong_ZHU          Jiahao_SHEN            wenqi_GAO 
+##                   31                   31                   31 
+##         Xiyun _ZHANG          Yingxin_XIE          Yifei_ZHANG 
+##                   31                   31                   24 
+##          Xiaojia_LIU            Yuxuan_GE        Zhixin _ZHENG 
+##                   22                   22                   20 
+## Stanley Si Heng_ZHAO          Yuting_ZHOU              Dan_LEI 
+##                   19                   16                   15 
+##          Xueshi_WANG            Zhouda_WU         Ruoyi _ZHANG 
+##                   14                   14                   12 
+##         Tianyu_CHANG           Xijia_WANG           yunzhao_WU 
+##                   12                   12                   12 
+##              JIE_YAO    Nicole_SCHLOSBERG           Yixiong_XU 
+##                   10                   10                   10 
+##        Zach_FRIEDMAN           Berj_AKIAN         Kaijie _FANG 
+##                   10                    9                    9 
+##            Rong_SANG          Yucheng_PAN      Amanda_OLIVEIRA 
+##                    8                    7                    6 
+##             Fei_WANG          Jiasheng_YU         Wenning_XIAO 
+##                    6                    6                    4 
+##           Yingxin_YE           Fangqi_LIU          Hyungoo_LEE 
+##                    2                    1                    1 
+##        Shuying_XIONG  Abdul Malik _MUFTAU         Ali _ALJABRI 
+##                    1                    0                    0 
+##            Chris_KIM           Danny_SHAN             He _CHEN 
+##                    0                    0                    0 
+##  Mahshad_DAVOODIFARD         Qianhui_YUAN         Sara_VASQUEZ 
+##                    0                    0                    0 
+##       Vidya_MADHAVAN           Yurui_WANG 
+##                    0                    0
+
sort(betweenness(PPlot),decreasing=TRUE)
+
##          Yifei_ZHANG Stanley Si Heng_ZHAO              Dan_LEI 
+##          260.6143603           97.2814961           76.1952381 
+##        Zhixin _ZHENG           Yingxin_YE          Xueshi_WANG 
+##           64.1176471           33.0000000           23.1132084 
+##    Nicole_SCHLOSBERG          Yuting_ZHOU        Zach_FRIEDMAN 
+##           19.4967508           19.2243431            9.3856397 
+##            Zhouda_WU          Guoliang_XU          Hangshi_JIN 
+##            9.2253968            6.9980008            6.9980008 
+##           Jiaao `_QI          Jiacong_ZHU          Jiahao_SHEN 
+##            6.9980008            6.9980008            6.9980008 
+##            wenqi_GAO         Xiyun _ZHANG          Yingxin_XIE 
+##            6.9980008            6.9980008            6.9980008 
+##           Yixiong_XU              JIE_YAO          Xiaojia_LIU 
+##            5.1357143            3.9579365            3.2007978 
+##            Yuxuan_GE          Yucheng_PAN  Abdul Malik _MUFTAU 
+##            3.2007978            0.8666667            0.0000000 
+##         Ali _ALJABRI      Amanda_OLIVEIRA           Berj_AKIAN 
+##            0.0000000            0.0000000            0.0000000 
+##            Chris_KIM           Danny_SHAN           Fangqi_LIU 
+##            0.0000000            0.0000000            0.0000000 
+##             Fei_WANG             He _CHEN          Hyungoo_LEE 
+##            0.0000000            0.0000000            0.0000000 
+##          Jiasheng_YU         Kaijie _FANG  Mahshad_DAVOODIFARD 
+##            0.0000000            0.0000000            0.0000000 
+##         Qianhui_YUAN            Rong_SANG         Ruoyi _ZHANG 
+##            0.0000000            0.0000000            0.0000000 
+##         Sara_VASQUEZ        Shuying_XIONG         Tianyu_CHANG 
+##            0.0000000            0.0000000            0.0000000 
+##       Vidya_MADHAVAN         Wenning_XIAO           Xijia_WANG 
+##            0.0000000            0.0000000            0.0000000 
+##           yunzhao_WU           Yurui_WANG 
+##            0.0000000            0.0000000
+
    +
  • 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.

+
+
+
+ + + + +
+ + + + + + + + + + + + + + +