【发布时间】:2018-07-25 10:16:43
【问题描述】:
如果顶点与另一个顶点相邻,则下面的代码用 1 填充矩阵,否则用 0 填充矩阵。我使用了this function for comparison,但结果矩阵很奇怪!!
R
library(igraph)
#prepare random data
random<-matrix(c(1,2,2,3,3,4),ncol=2,byrow=TRUE)
graph<-graph.data.frame(random, directed = FALSE)
v1<-c()
v2<-c()
for (edge in 1:length(E(graph))){
ver1<-ends(graph = graph, es = edge)[1]
v1[edge]<-ver1
ver2<-ends(graph = graph, es = edge)[2]
v2[edge]<-ver2
}
v1
[1] "1" "2" "3"
#Construct the matrix
n1<-matrix(,nrow=length(v1), ncol=length(V(graph)))
for(i in 1:length(v1)){
for(j in 1:length(V(graph))){
are_adjacent(graph, v1[i], V(graph)[j])
if(TRUE){
n1[i,j]<-1
}
else{
n1[i,j]<-0
}
}
}
n1
[,1] [,2] [,3] [,4]
[1,] 1 1 1 1
[2,] 1 1 1 1
[3,] 1 1 1 1
虽然结果矩阵应该是:
n1
[,1] [,2] [,3] [,4]
[1,] 0 1 0 0
[2,] 1 0 1 0
[3,] 0 1 0 1
因为1 is adjacent only to 2、2 is adjacent to 1 & 3、3 is adjacent to 2 & 4、4 is adjacent only to 3
提前致谢
【问题讨论】:
标签: r loops matrix igraph adjacency-matrix