根据以 R 为基数的节点向量给出的路径创建邻接矩阵

Create adjacency matrix from a path given as a vector of nodes in base R

给定基 R 中显示的形式(参见代码摘录)的向量,是否有一种紧凑而优雅的方法来创建邻接矩阵?

我在下面给出了我最好的尝试。理想情况下,我想一步创建已经填充的邻接矩阵,而不是必须创建矩阵数据结构然后填充它。

p <- 25 # Cardinality of vertex set; Number of nodes
  
hypothesis_path <- c(17, 7, 6, 1) # path in this form

path_to_D <- function(hypothesis_path, p) {
  path_len <- length(hypothesis_path) - 1
  idx_path <- t(sapply(1:path_len, function(i) hypothesis_path[i:(i+1)]))
  D <- matrix(0, p, p); D[idx_path] <- 1
  D
}

D <- path_to_D(hypothesis_path, p)

which(D == 1, arr.ind = TRUE)

# Desired indices of adjacency matrix are populated (with ones)
#      row col
# [1,]   6   1
# [2,]   7   6
# [3,]  17   7

可接受的答案将避免使用 igraph 或类似的,并将使用给定形式的路径向量。也就是说,建议和替代方案当然总是受到欢迎和赞赏。

您可以使用强大但 little-known 的 matrix-based 索引技巧:

index_mat <- rbind(
               c(1, 2),
               c(2, 3), 
               c(3, 1)
             )

mat <- matrix(FALSE, 3, 3)
mat[index_mat] <- TRUE
mat
      [,1]  [,2]  [,3]
[1,] FALSE  TRUE FALSE
[2,] FALSE FALSE  TRUE
[3,]  TRUE FALSE FALSE

所以这样做:

path_to_D <- function (path, p) {
  indices <- cbind(path[-length(path)], path[-1])
  D <- matrix(0, p, p)
  D[indices] <- 1
  D
}

D <- path_to_D(hypothesis_path, 25)
which(D == 1, arr.ind=TRUE)

     row col
[1,]   6   1
[2,]   7   6
[3,]  17   7

您可以使用 Matrix 包中的稀疏矩阵。它不是基础 R,而是一个非常常见的包。

library(Matrix)

hypothesis_path <- c(17, 7, 6, 1)

D <- sparseMatrix(i = hypothesis_path[-length(hypothesis_path)],
                  j = hypothesis_path[-1])

which(D == 1, arr.ind = TRUE)
     row col
[1,]   6   1
[2,]   7   6
[3,]  17   7