问题
I have a list like that:
> 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
Now I want to turn this list into an adjacency matrix so that I can then build a graph undirect not simple (there may be multilinks and selfloops).
This list should be read in pairs, that is, (1 4) indicates that there is a link from node 1 to node 4, the pair (1 2) indicates that there is a link from node 1 to node 2, etc.
How can I do this?
I thought I iterate the list with a for loop with step = 2 but I haven't found how to do. And I'm not sure how to assign the values of the matrix, what I assing to multilinks?
Thanks a lot
回答1:
Here's another way
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
回答2:
I suspect something like this is what you are looking for:
# 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))
Btw, list may not be the best name for a list.
来源:https://stackoverflow.com/questions/36378237/from-list-to-adjacency-matrix