I have a graph object g
and would like to create a subgraph g_sub
of the neighborhood of a set of vertices v_matches
in g
, with order
1.5.
In other words I want to find which vertices are connected to v_matches
(order 1), and which vertices are connected to the order==1 vertices if and only if these are also connected to the v_matches
vertices.
In non-technical terms I want to find 'friends of friends (order 2), provided that these friends are also my friends (order 1.5)'. I cannot find a way to do this easily in igraph
.
The code I have written calculates order 2 neighborhood of v_matches
, but I want it to calculate order 1.5. Any help is very much appreciated.
v_matches <- which(V(g)$SomeVertexAttribute==SomeValue)
g_sub <- induced.subgraph(graph=g,vids=unlist(neighborhood(g,order=2,nodes=v_matches)))
UPDATE: Here is a function and some code I wrote to convert an order=2
subgraph to order 1.5
. However, I am not convinced it is working properly.
Order2ToOrder1.5 <- function(g_sub,categoryValue) {
# get the new indexes of the 'ego' sites for the subgraph
matches_subgraph_gsub <- which(V(g_sub)$`Categorical 1`==categoryValue)
# get the edge list of the subgraph
edgelistTemp <- get.edgelist(g_sub)
# get unique "from" values
uniqueFrom <- unique(edgelistTemp[,1])
badVerts <- c() # yes, I know it is bad form to append to a vector using a for loop...
for (i in 1:length(uniqueFrom)){
# we find the immediate neighbours of each vertice
tempGraph <- as.vector(neighborhood(graph=g_sub,order=1,nodes=uniqueFrom[i])[[1]])
# if the neighbourhood does not contain one of the 'ego' sites (i.e. in matches_subgraph_gsub), then we flag this vertex for deletion
matchTemp <- match(tempGraph,matches_subgraph_gsub)
if (length(which(is.na(matchTemp)))==length(matchTemp)) {badVerts <- append(badVerts,uniqueFrom[i])}
}
# now we can delete these from the subgraph:
g_return <- delete.vertices(g_sub,badVerts)
}
categoryValue <- 21
matches <- which(V(g)$`Categorical 1`==categoryValue)
g_sub <- induced.subgraph(graph=g,vids=unlist(neighborhood(graph=g,order=2,nodes=matches)))
# We can use the new function to convert from order2 to order1.5:
g_sub_1.5 <- Order2ToOrder1.5(g_sub,categoryValue)