# Run this lines once to install packages on your machine
# install.packages("lda")
# install.packages("igraph")
# install.packages("networkD3")
# Run these lines once per session to load packages
library(lda)
library(igraph)
library(networkD3)
data(sampson) # load the monks data from lda
samplk1 <- sampson$SAMPLK1 # extract one of the matricesProject 1: Sampson’s Monks
In this project, you will analyze and model Sampson’s Monks dataset, a classic dataset in social network analysis.
By completing this project, you will:
- Work with matrices and lists in applied settings
- Practice row/column operations for network statistics
- Use functions, control flow, and libraries
- Understand the contrast between random vs. real-world networks
There are two components: the worksheet and the project. The worksheet will help you familiarize yourself with the computational tools you’ll need. This should be done first. The project is the main event: your analysis of the data set.
You will submit:
- A worksheet .R file with your well-commented code
- A project .R file with your well-commented code.
Both files should be submitted to their respective Pensive assignments before your scheduled Project Studio.
Matrices
Section 1: Matrices + Operations
Three students take a class together and study for a project, midterm, and final together.
- Student A scores:
12, 23, 34
- Student B scores:
45, 56, 67
- Student C scores:
78, 89, 64
Q1: Create a matrix containing their scores.
Use matrix() to create the 3x3 matrix:
Q2: Name the rows and columns
Use colnames() and rownames() to label rows and columns.
Q3: Compute each student’s average score
Which student has the highest average?
Plots
Q4: How can we make simple graphs in Base R?
Read the documention for plot(), boxplot(), and hist() and run at least one example of each.
Q5: Create a histogram using the matrix scores
Hint: Convert the matrix to a normal vector first using as.vector().
Q6: Use the built-in airquality dataset
This dataset contains daily New York air quality measurements from May–September 1973 spread across several vectors.
airquality$Ozone: Ozone concentration (ppb)
airquality$Solar.R: Solar radiation (langley)
airquality$Wind: Wind speed (mph)
airquality$Temp: Temperature (°F)
airquality$Month: Month (5 = May, …, 9 = September)
airquality$Day: Day of the month
a) Construct a histogram of Ozone
b) Construct a scatterplot of Ozone vs Temperature
c) Construct a boxplot of Temperature by Month
Intro to Packages
Q7: Install and load the packages
Install and load the igraph and networkD3 packages by running the following code:
install.packages("igraph") # you only need to run this line once
install.packages("networkD3") # you only need to run this line once
library("igraph")
library("networkD3")Q8: What are igraph and networkD3?
How are these libraries useful for network analysis and visualization? Browse their documentation here: https://r.igraph.org/, http://christophergandrud.github.io/networkD3/.
Q9: Explore usage
Run these examples and describe what they do.
a) igraph example
g <- graph(edges = c(1,2, 2,3, 3,1), n = 3, directed = FALSE)
plot(g)b) networkD3 example
simpleNetwork(data.frame(source = c("A", "B", "C"),
target = c("B", "C", "A")))Part 0: Setting Up
Open your R app and install and load the necessary packages for this project: lda, igraph, and networkD3. lda contains the monks data.
sampson contains 10 different matrices, each one a sociomatrix that describes the network of a different type of relationship. All 10 matrices describe the same 18 monks, in the same row and column order.
| Name | Relation |
|---|---|
| SAMPLK1, SAMPLK2, SAMPLK3 | Liking, at three successive time points |
| SAMPDLK | Disliking |
| SAMPES | Esteem |
| SAMPDES | Disesteem |
| SAMPIN | Positive influence |
| SAMPNIN | Negative influence |
| SAMPPR | Praise |
| SAMNPR | Blame (negative praise) |
In each network, each node represents a single monk and each edge represents a relationship pointing from one monk to another. Every monk was asked to name only his top three choices on each relationship. Paradoxically, a monk’s first choice gets a 3 (3 points) while his third choice gets a 1 (1 point); a 0 means “not nominated”.
Part 1: Visualizing the Network
Create two network visualizations select one of Sampson’s matrices (not SAMPLK1) that describe monk relationships and form two plots:
- A static plot using
igraph::plot.igraph() - An interactive plot using
networkD3::forceNetwork()
Before plotting, check what data structure your plotting function accepts and create it accordingly. networkD3 requires dataframes of nodes and edges, not a sociomatrix. You can use the following code to convert one of Sampson’s matrices (called monk_mat here) into the structures that networkD3 expects.
nodes <- data.frame(name = rownames(monk_mat), group = 1)
edges <- which(monk_mat > 0, arr.ind = TRUE)
links <- data.frame(
source = edges[, "row"] - 1,
target = edges[, "col"] - 1,
value = monk_mat[edges]
)Try visualizing a few different matrices before deciding on one that you find most interesting. Read the documentation on each of the plotting functions to understand the arguments they make available, then tune the plots to your liking.
Part 2: Summary Statistics on a Sociomatrix
A picture of a network is suggestive but hard to reason about precisely. Summary statistics let us describe the same structure numerically. A few terms first.
- Node: one monk. There are 18, one per row and one per column.
- Edge: a nomination from one monk to another. Edges here are directed: monk \(i\) nominating monk \(j\) (row \(i\), column \(j\)) is not the same as monk \(j\) nominating monk \(i\).
- Edge weight: the number in the cell, 3, 2, or 1, recording whether the nomination was that monk’s first, second, or third choice. A
0means there is no edge. - Out-degree of a node: the number of edges originating at it, i.e. how many other monks that monk nominated.
- In-degree of a node: the number of edges pointing to it, i.e. how many other monks nominated that monk.
- Out-strength and in-strength: the sum of the edge weights leaving or arriving at a node. These credit a first-choice nomination more heavily than a third-choice one.
Solutions below use SAMPDLK (disliking) as the chosen matrix; student answers will differ depending on their choice.
Report which matrix you chose, and describe in one sentence what a large value means for that relation (e.g. for
SAMPDLK, a high in-degree means a monk was frequently named as disliked).Compute the out-degree and in-degree of each monk.
rowSums()andcolSums()will do this in one line each, once you have turned the weights intoTRUE/FALSEvalues with a comparison such asmonk_mat > 0.Compute the out-strength and in-strength of each monk.
Make a histogram of in-degree and a histogram of in-strength. Compare their shapes to a histogram of out-degree. Why is the out-degree distribution so much narrower? (Look back at how the monks were surveyed.)
Make a scatterplot of in-degree against in-strength, one point per monk. What would it mean for a monk to fall well above or well below the general trend?
Which monk received the most nominations on your chosen relation, and which received the fewest? Do you get the same answer using in-degree as you do using in-strength? If not, explain the disagreement.
Part 4: Model vs Observations
Apply the same techniques you used in parts 1 and 2 (visualization and summary statistics) to describe the structure of the network that was simulated by your model. In 3-5 sentences, compare these networks: In what ways is the observed network monk_mat similar to your generated network? In what ways is it different? What patterns appear in the observed network that are missing from your generated one?