计算R中两个顶点之间共同的邻居数

时间:2015-11-16 16:11:44

标签: r vertex neighbours

我试图计算两个顶点之间共同的邻居数量。

测试文件包含

1 2

1 4

1 5

2 3

2 4

2 5

3 4

y<-read.table("test.txt")

require(igraph)

g<-graph.data.frame(y, directed=F, vertices=NULL)

for(i in 1:5)
{
  for(j in 1:5)
{

c[i,j]<-cocitation(g,i)[j]

}}

y$neigC<-c[y$V1,y$V2]

但是,当我尝试将其添加到数据框时,它无法给出正确答案。

1 个答案:

答案 0 :(得分:1)

试试这个:

y<-structure(list(V1 = c(1L, 1L, 1L, 2L, 2L, 2L, 3L),
                  V2 = c(2L, 4L, 5L, 3L, 4L, 5L, 4L)),
             .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA, -7L))

require(igraph)
g<-graph.data.frame(y, directed=F, vertices=NULL)
d<-cocitation(g)
y[,3]<-sapply(1:nrow(y),function(x){d[y[x,1],y[x,2]]}) # or diag(d[y[,1],y[,2]])

 y
  V1 V2 V3
1  1  2  2
2  1  4  1
3  1  5  1
4  2  3  1
5  2  4  2
6  2  5  1
7  3  4  1

这里是g

enter image description here

d(我重命名)看起来像这样:

unname(d)
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    2    2    1    1
[2,]    2    0    1    2    1
[3,]    2    1    0    1    1
[4,]    1    2    1    0    2
[5,]    1    1    1    2    0

那是你的预期吗?