Skip to content

Instantly share code, notes, and snippets.

@JoGall
Created May 11, 2018 09:26
Show Gist options
  • Save JoGall/4d76942b98d6ce80b89bac8d2df03853 to your computer and use it in GitHub Desktop.
Save JoGall/4d76942b98d6ce80b89bac8d2df03853 to your computer and use it in GitHub Desktop.
# Computes number of neighbours in common between first degree neighbourhood of each vertex in an igraph network
# Not sure if this is meaningful metric yet but seems like it could be interesting!
# FUNCTION --------------------------------------------------------------------
common.neighbours <- function(graph) {
lapply(unique(V(graph)), function(v) {
# get vertices of 1st-order neighbourhood for focal vertex (and omit self)
n1 <- ego(graph, 1, v)[[1]] %>% as.vector()
n1 <- n1[!n1 %in% v]
# get vertices of 1st-order neighbourhood for each neighbour (and omit self from each)
n1n <- ego(graph, 1, n1) %>% lapply(as.vector)
n1n <- mapply(setdiff, n1n, n1, SIMPLIFY = FALSE)
# count vertices in common between neighbourhood and focal vertex
x <- lapply(n1n, function(x) x %in% n1 %>% sum)
Reduce("+", x) / 2
}) %>%
unlist(use.names = F)
}
# EXAMPLES --------------------------------------------------------------------
# 1. No common vertices in 1st order neighbourhood of each vertex
nodes0 <- data.frame(id = 1:10)
edges0 <- data.frame(to = c(10,10,10,10,3,1,4,4,1),
from = c(1,2,3,4,5,6,7,8,9))
g0 <- graph_from_data_frame(edges0, nodes0, directed = F)
plot(g0)
common.neighbours(g0)
# 2. Several common vertices in 1st order neighbourhood of each vertex
nodes1 <- data.frame(id = 1:10)
edges1 <- data.frame(to = c(10,10,10,10,3,3,1,4,4,1,2,6),
from = c(1,2,3,4,4,5,6,7,8,9,3,9))
g1 <- graph_from_data_frame(edges1, nodes1, directed = F)
plot(g1)
common.neighbours(g1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment