我想将前向恒星表示转换为入射矩阵

时间:2019-10-29 20:45:52

标签: r graph

我有一个前向恒星表示形式,我想转换成我编写代码的入射矩阵,但这给了我错误的答案

FS <- data.frame(
    archsNo = c(1:12),
    snode = c(1,1,2,2,3,3,4,4,5,5,6,8),
    enode = c(2,4,4,5,2,5,6,7,7,8,7,7)) 
print(FS)
   archsNo snode enode
1        1     1     2
2        2     1     4
3        3     2     4
4        4     2     5
5        5     3     2
6        6     3     5
7        7     4     6
8        8     4     7
9        9     5     7
10      10     5     8
11      11     6     7
12      12     8     7

这是我尝试过的:

n = 8 #number of nodes 
m = 12 #number of archs
incidence <- matrix(0L,nrow=n, ncol=m)
for(row in 1:n)
{
  for(col in 1:m)
  {
   incidence[row][col] = ifelse(row == snode[col],1,ifelse(row == enode[col],-1,0)) 
   row 
   snode[col]
   enode[col]

  }
}
incidence

这是结果:

[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,]    1    0    0    0    0    0    0    0    0     0     0     0
[2,]   -1    0    0    0    0    0    0    0    0     0     0     0
[3,]    0    0    0    0    0    0    0    0    0     0     0     0
[4,]    0    0    0    0    0    0    0    0    0     0     0     0
[5,]    0    0    0    0    0    0    0    0    0     0     0     0
[6,]    0    0    0    0    0    0    0    0    0     0     0     0
[7,]    0    0    0    0    0    0    0    0    0     0     0     0
[8,]    0    0    0    0    0    0    0    0    0     0     0     0

对于每个单元格,如果该行中的节点是起始节点,则它应包含1(如果结束节点),则该单元格应具有-1,否则为0,但这没有发生

1 个答案:

答案 0 :(得分:0)

您不使用[row][col]为R中的数组建立索引,而是使用[row,col]。但这是另一种无需循环即可轻松填充矩阵的方法

nodes <- max(FS$snode, FS$enode)

mm <- matrix(0, nrow=nodes, ncol=nrow(FS))
mm[cbind(FS$snode, FS$archsNo)] <- 1
mm[cbind(FS$enode, FS$archsNo)] <- -1
mm

#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
# [1,]    1    1    0    0    0    0    0    0    0     0     0     0
# [2,]   -1    0    1    1   -1    0    0    0    0     0     0     0
# [3,]    0    0    0    0    1    1    0    0    0     0     0     0
# [4,]    0   -1   -1    0    0    0    1    1    0     0     0     0
# [5,]    0    0    0   -1    0   -1    0    0    1     1     0     0
# [6,]    0    0    0    0    0    0   -1    0    0     0     1     0
# [7,]    0    0    0    0    0    0    0   -1   -1     0    -1    -1
# [8,]    0    0    0    0    0    0    0    0    0    -1     0     1