问题
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)
}
sample data:
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)
for example:
commonNeighbors(c(1,15),Graph)
the result: [1] 5
Levels: 1 5 6 10 14 15
another example:
commonNeighbors(c(2,4),Graph)
the result: factor(0)
Levels: 2 4 8 10 11 12 13 14
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)
Ideal result for example 1: 5
Ideal result for example 2: NULL
回答1:
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)
}
}
来源:https://stackoverflow.com/questions/60816290/find-common-neighbors-of-selected-vertices