我想获得图中每对节点之间相互连接的节点列表:
library(igraph)
G <- graph(c(1,2,1,3,1,4,2,4, 2,3,2,5,3,5,4,5,5,6,5,7,7,8,7,9), directed=F)
plot(G)
例如,在此图中,节点 1 和 2 共享公共节点 3 和 4。节点 1 和 3 共享公共节点 2。我想获取此列表或作为数据帧的格式。
是否有一个命令可以获取类似以下任一内容的命令:
(1)
node1 node2 mutual
1 2 3, 4
1 3 2
1 4 2
2 3 1, 5
or (2)
node1 node2 mutual
1 2 3
1 2 4
1 3 2
1 4 2
2 3 1
2 3 5
我能够使用以下代码获取两个节点之间的相互节点数:
# function to count the number of mutual friends between every pair of nodes
mutual_friends <- function(G) {
# initialize an emptry matrix to store number of mutual friends between pairs of nodes
num_nodes <- vcount(G)
mutual_friends <- matrix(0, nrow=num_nodes, ncol=num_nodes)
# loop over each node
for (node in 1:num_nodes) {
# get this node's list of friends
friends <- neighbors(G, node)
# add a count of 1 between all pairs of the node's friends
for (i in friends)
for (j in friends)
mutual_friends[i, j] = mutual_friends[i, j] + 1
}
# make the output readable with column names
dimnames(mutual_friends) <- list(row=V(G)$name, col=V(G)$name)
diag(mutual_friends) <- NA
mutual_friends
}
(编码归功于:https://rstudio-pubs-static.s3.amazonaws.com/72599_65ecae185590432cb2373df4825d2ef9.html#connected-components https://rstudio-pubs-static.s3.amazonaws.com/72599_65ecae185590432cb2373df4825d2ef9.html#connected-components
但我正在努力获取每对节点之间的相互节点列表。
我感谢任何建议和帮助。谢谢!