if else 循环产生的奇怪矩阵

strange matrix result from if else loop

如果顶点与另一个顶点相邻,则下面的代码用 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 22 is adjacent to 1 & 33 is adjacent to 2 & 44 is adjacent only to 3

提前致谢

错误是你的if语句:

试试这个:

n1<-matrix(,nrow=length(v1), ncol=length(V(graph)))
for(i in 1:length(v1)){
  for(j in 1:length(V(graph))){
    adjacent_test <- are_adjacent(graph, v1[i], V(graph)[j])
    if(adjacent_test == TRUE){
      n1[i,j]<-1
    }
    else{
      n1[i,j]<-0
    }
  }
}