返回R中每对节点之间的相互节点列表 [英] Return a list of mutual nodes between every pair of nodes in R

查看:0
本文介绍了返回R中每对节点之间的相互节点列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要获取图表中每对节点之间相互连接的节点的列表:

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

或(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

但我很难获得每对节点之间的相互节点的列表。 我感谢任何形式的建议和帮助。谢谢!

推荐答案

这不是很有效,这是暴力双重循环,但您可以

get_mutuals <- function(g) {
  do.call("rbind", lapply(seq.int(1, vcount(g)-1), function(i) {
    do.call("rbind", lapply(seq.int(i+1, vcount(g)), function(j) {
      ni <- neighbors(g, i)
      nj <- neighbors(g, j)
      overlap <- intersect(ni, nj)
      if (length(overlap) & i %in% nj) {
        data.frame(i=i, j=j, m=overlap)
      } else {
        NULL
      }
    }))
  }))
}
get_mutuals(G)

这将为您提供类似于您的版本2的输出。

   i j m
1  1 2 3
2  1 2 4
3  1 3 2
4  1 4 2
5  2 3 1
   ...

如果您想要更多类似的内容,可以切换到data.frame(i=i, j=j, m=toString(overlap))将所有值粘贴到列中。

另一种可能是像这样迭代边

get_mutuals <- function(g) {
  do.call("rbind", lapply(seq.int(1, gsize(g)), function(i) {
    edge <- ends(g, i)
    i <- edge[1, 1]
    j <- edge[1, 2]
    ni <- neighbors(g, i)
    nj <- neighbors(g, j)
    overlap <- intersect(ni, nj)
    if (length(overlap)) {
      data.frame(i=i, j=j, m=overlap)
    } else {
      NULL
    }
  }))
}
get_mutuals(G)

这篇关于返回R中每对节点之间的相互节点列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆