r create adjacency matrix or edge list from adjacency list

橙三吉。 提交于 2019-12-24 07:26:24

问题


I have an adjacency list and I am trying to make it into and adjacency matrix or edge list. This is in order to conduct network analysis on the network built from the adjacency matrix or edge list. I am using R. An example of adjacency list is as follows (each row has different amount of entries, and the empty entries are NA):

[17,50,90,NA,NA;
80,67,NA,NA,NA;
33,31,32, NA,NA;
33,31,32,NA,NA;
354,56,87,97,32;
....]

I tried using R: Adjacency list to Adjacency matrix but this only works if my adjacency list has two entries (ie there are more than two neighbors in a group). I get an edge list but only taking into account the first two entries in my list.

I also tried using From list to adjacency matrix but using igraph and make_graph(unlist(mydata)) led to the error: "At type_indexededgelist.c:117 : cannot create empty graph with negative number of vertices, Invalid value"

I need an adjacency matrix which takes into account the weights that would be in the network (like if entry 31 and 32 are in two rows, then their edge weight would be 2). Thank you for any help.


回答1:


I have an adjacency list and I am trying to make it into an[...] edge list.

Maybe you could do

lst <- read.csv(header=F, comment.char=";", colClasses="integer", text="
17,50,90,NA,NA;
80,67,NA,NA,NA;
33,31,32,NA,NA;
33,31,32,NA,NA;
354,56,87,97,32;")
m <- as.matrix(lst)
e <- stack(split(m, row(m)))[,2:1]
(e <- e[complete.cases(e),])
# 1    1     17
# 2    1     50
# 3    1     90
# 6    2     80
# 7    2     67
# 11   3     33
# 12   3     31
# 13   3     32
# 16   4     33
# 17   4     31
# 18   4     32
# 21   5    354
# 22   5     56
# 23   5     87
# 24   5     97
# 25   5     32

or

e <- apply(lst, 1, function(x)x[!is.na(x)])
(e <- do.call(rbind, lapply(e, embed, 2))[,2:1])
#      [,1] [,2]
# [1,]   17   50
# [2,]   50   90
# [3,]   80   67
# [4,]   33   31
# [5,]   31   32
# [6,]   33   31
# [7,]   31   32
# [8,]  354   56
# [9,]   56   87
# [10,]   87   97
# [11,]   97   32

depending on what you need/what your "adjacency list" represents.



来源:https://stackoverflow.com/questions/47256744/r-create-adjacency-matrix-or-edge-list-from-adjacency-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!