查找选定顶点的公共邻居

问题描述 投票:2回答:1

我编写了一个函数,该函数获取顶点列表和igraph加权有向图。我想找到输入顶点的公共邻居。这是我的功能:

commonNeighbors <- function(v,g)
{
   library(igraph)
   library(dplyr)
   allNeigh <- list()
   for (i in v)
   {
      allNeigh <- append(allNeigh,c(neighbors(as.undirected(g),paste(i,sep=""))$name))
   }
   allNeigh <- cbind(allNeigh)
   allNeigh <- table(as.numeric(allNeigh))
   allNeigh <- as.data.frame(allNeigh)
   colnames(allNeigh) <- c('vertexID','freq')
   allNeigh <- allNeigh %>% dplyr::filter (freq > 1 & !vertexID %in% v )
   return(allNeigh$vertexID)
 }

样本数据:

library(igraph)

x <- read.table(text = "
from    to  weight
1   2   0.2
1   7   0.5
2   5   0.9
2   6   1
3   4   0.4
3   8   0.6
4   3   0.7
5   8   0.23
6   10  0.24
6   9   0.25
7   1   0.69
7   11  0.75
8   10  0.98
9   12  0.41
9   13  0.32
9   6   0.77
9   15  0.63
10  6   0.21
10  15  0.02
11  14  0.98
12  14  0.54
12  9   0.69
13  14  0.41
15  9   1
14  5   0.63
14  15  0.5
6   14  0.21
10  4   0.68
2   8   0.66
11  1   0.69
1   6   0.25
7   12  0.17
", header = TRUE)

Graph <- graph_from_data_frame(x)
E(Graph)$weight <-  x$weight

set.seed(1); plot(Graph)

enter image description here

例如:

commonNeighbors(c(1,15),Graph)
the result: [1] 5
            Levels: 1 5 6 10 14 15

另一个例子:

commonNeighbors(c(2,4),Graph)
the result: factor(0)
            Levels: 2 4 8 10 11 12 13 14

我要做的第一件事是删除级别:2 4 8 ....第二个是如果没有公共邻居,则返回null,而不是factor(0)

例如,理想结果为1:5示例2的理想结果:NULL

r list function igraph vertices
1个回答
1
投票

使用以下代码解决了此问题:

commonNeighbors <- function(v,g)
{
  library(igraph)
  library(dplyr)
  allNeigh <- list()
  for (i in v)
  {
    allNeigh <- append(allNeigh,c(neighbors(as.undirected(g),paste(i,sep=""))$name))
  }
  allNeigh <- cbind(allNeigh)
  allNeigh <- table(as.numeric(allNeigh))
  allNeigh <- as.data.frame(allNeigh)
  colnames(allNeigh) <- c('vertexID','freq')
  allNeigh <- allNeigh %>% dplyr::filter (freq > 1 & !vertexID %in% v )
  allNeigh <- as.matrix(allNeigh)
  if(length(allNeigh > 0))
  {
    allNeigh <- as.data.frame(allNeigh)
    return(as.matrix(allNeigh$vertexID))
  }
  else
  {
    return(NULL)
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.