查找选定顶点的公共邻居 [英] Find common neighbors of selected vertices

查看:86
本文介绍了查找选定顶点的公共邻居的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wrote a function that gets a list of vertices and an igraph weighted and directed graph. I want to find the common neighbors of input vertices. here is my function:

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)

例如:

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)

first thing I want to do is deleting the levels: 2 4 8 .... and the second is if there is not a common neighbor return null, not factor(0)

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

Ideal result for example 1: 5
Ideal result for example 2: NULL

推荐答案

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

This problem is solved using this code:

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)
  }
}

这篇关于查找选定顶点的公共邻居的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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