Skip to content

Instantly share code, notes, and snippets.

@jrladd
Created April 16, 2021 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrladd/7064a20251b00d46076c69db7f5dbc95 to your computer and use it in GitHub Desktop.
Save jrladd/7064a20251b00d46076c69db7f5dbc95 to your computer and use it in GitHub Desktop.
Code for network analysis tutorial using R
####################################
# Code for network analysis tutorial using R
####################################
# Import necessary libraries
library(tidyverse)
library(igraph)
library(networkD3)
# Read in edgelist CSV
edges <- read_csv("~/Downloads/got-edges.csv")
# Create igraph object from edgelist
G <- graph_from_data_frame(d = edges, directed = FALSE)
E(G)$weight <- E(G)$Weight #Make sure weight is labeled correctly
# Create a default node-link diagram, notice how this isn't very readable!
plot(G)
# Create a basic interactive network graph with D3
simpleNetwork(edges, opacity=1, zoom=TRUE)
# Calculate degree using igraph
degree(G)
V(G)$degree <- degree(G) # Add results as a vertex attribute
# Calculate betweenness centrality using igraph
betweenness(G, normalized=TRUE)
V(G)$betweenness <- betweenness(G, normalized=TRUE) # Add results as vertex attribute
# Find the node with the highest degree
V(G)$name[V(G)$degree == max(V(G)$degree)]
# Find the node with the highest betweenness
V(G)$name[V(G)$betweenness == max(V(G)$betweenness)]
# Optional: calcucate betweenness divided by degree, find node with highest value
# (i.e. This is the node that functions most as a "bridge")
betweenness_over_degree <- betweenness(G)/degree(G)
V(G)$name[betweenness_over_degree == max(betweenness_over_degree)]
# Create a histogram of the degree distribution
ggplot(data = tibble(degree(G))) +
geom_histogram(mapping = aes(x = degree(G)), binwidth = 0.5)
# Create a histogram of the betweenness distribution
ggplot(data = tibble(betweenness(G))) +
geom_histogram(mapping = aes(x = betweenness(G)), binwidth = 50)
# Build a nicer-looking visualization:
# Convert data to networkD3-friendly format & calculate modularity clusters
G_d3 <- igraph_to_networkD3(G, membership(cluster_fast_greedy(G))
# Add degree to node data
G_d3$nodes$degree <- V(G)$degree
# Create force network with nodes sized by degree and colored by modularity
forceNetwork(Links=G_d3$links, Nodes = G_d3$nodes, Source = 'source', Target = 'target', NodeID = 'name', Group = 'group', zoom = TRUE, opacity = 1, Value= 'value', Nodesize='name')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment