从列表到邻接矩阵

时间:2016-04-02 20:16:20

标签: r adjacency-matrix

我有一个这样的清单:

> print(list)
[[1]]
[1] 1

[[2]]
[1] 4

[[3]]
[1] 1

[[4]]
[1] 2

[[5]]
[1] 2

[[6]]
[1] 3

[[7]]
[1] 2

[[8]]
[1] 5

[[9]]
[1] 1

[[10]]
[1] 2

[[11]]
[1] 3

[[12]]
[1] 7

[[13]]
[1] 3

[[14]]
[1] 4

[[15]]
[1] 3

[[16]]
[1] 5

[[17]]
[1] 1

[[18]]
[1] 1

[[19]]
[1] 4

[[20]]
[1] 6

现在我想将此列表转换为邻接矩阵,以便我可以构建一个非直接的图形(可能有多链接和自循环)。

此列表应成对读取,即(1 4)表示存在从节点1到节点4的链接,对(1 2)表示存在从节点1到节点的链接2,等等。

我该怎么做?

我以为我使用步骤= 2的for循环迭代列表,但我还没找到怎么做。 而且我不确定如何分配矩阵的值,我对多链路的贡献是什么?

非常感谢

2 个答案:

答案 0 :(得分:0)

我怀疑这是你想要的东西:

# Input
my_list <- list(1, 4, 1, 2, 2, 3, 2, 5, 1, 2, 3, 7, 3, 4, 3, 5, 1, 1, 4, 6)

# Make to vector
my_list <- unlist(my_list)

# Number of vertices in graph (may change this to any number > max(my_list))
num_vertices <- max(my_list)

# Number of edges
num_edges <- length(my_list) / 2

# Transform edge data into data.frame, each row is an edge
edges <- data.frame(tails = my_list[rep(c(TRUE, FALSE), num_edges)],
                    heads = my_list[!rep(c(TRUE, FALSE), num_edges)])

# Count duplicate edges (if multi-edges should not be allowed, set count to 1)
edges$count <- ave(rep(1, num_edges), edges, FUN = base::sum)

# Remove duplicate edges, count encodes multi-edges
edges <- edges[!duplicated(edges), ]

# Make empty adjacency matrix
adjacency_matrix <- matrix(0, ncol = num_vertices, nrow = num_vertices)

# Populate matrix
adjacency_matrix[as.matrix(edges[, c("heads", "tails")])] <- edges$count

# Make graph undirected
adjacency_matrix <- adjacency_matrix + t(adjacency_matrix) - diag(diag(adjacency_matrix))

顺便说一下,list可能不是列表的最佳名称。

答案 1 :(得分:0)

这是另一种方式

lst <- list(1, 4, 1, 2, 2, 3, 2, 5, 1, 2, 3, 7, 3, 4, 3, 5, 1, 1, 4, 6)
library(igraph)
g <- make_graph(unlist(lst), directed = F)
( m <- as_adjacency_matrix(g, sparse = F) ) 
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,]    1    2    0    1    0    0    0
# [2,]    2    0    1    0    1    0    0
# [3,]    0    1    0    1    1    0    1
# [4,]    1    0    1    0    0    1    0
# [5,]    0    1    1    0    0    0    0
# [6,]    0    0    0    1    0    0    0
# [7,]    0    0    1    0    0    0    0