问题描述
我的问题很简单:我需要从边列表创建邻接列表/矩阵.
My problem is very simple: I need to create an adjacency list/matrix from a list of edges.
我将一个边缘列表存储在csv文档中,其中column1 = node1,column2 = node2,我想将其转换为加权邻接列表或加权邻接矩阵.
I have an edge list stored in a csv document with column1 = node1 and column2 = node2 and I would like to convert this to a weighted adjacency list or a weighted adjacency matrix.
更准确地说,这是数据的样子-其中数字只是节点ID:
To be more precise, here's how the data looks like -where the numbers are simply node ids:
node1,node2
551,548
510,512
548,553
505,504
510,512
552,543
512,510
512,510
551,548
548,543
543,547
543,548
548,543
548,542
关于如何实现从此到加权邻接表/矩阵的转换的任何技巧?这就是我以前决心这样做的方式,但没有成功(由 Dai Shizuka 提供) :
Any tips on how to achieve the conversion from this to a weighted adjacency list/matrix?This is how I resolved to do it previously, without success (courtesy of Dai Shizuka):
dat=read.csv(file.choose(),header=TRUE) # choose an edgelist in .csv file format
el=as.matrix(dat) # coerces the data into a two-column matrix format that igraph likes
el[,1]=as.character(el[,1])
el[,2]=as.character(el[,2])
g=graph.edgelist(el,directed=FALSE) # turns the edgelist into a 'graph object'
谢谢!
推荐答案
此响应仅使用基数R.结果是一个用于表示邻接矩阵的标准矩阵.
This response uses base R only. The result is a standard matrix used to represent the adjacency matrix.
el <- cbind(a=1:5, b=5:1) #edgelist (a=origin, b=destination)
mat <- matrix(0, 5, 5)
mat[el] <- 1
mat
# [,1] [,2] [,3] [,4] [,5]
#[1,] 0 0 0 0 1
#[2,] 0 0 0 1 0
#[3,] 0 0 1 0 0
#[4,] 0 1 0 0 0
#[5,] 1 0 0 0 0
这里mat
是从边列表el
定义的邻接矩阵,它是向量1:5
和5:1
的简单cbind
.
Here mat
is your adjacency matrix defined from edgelist el
, which is a simple cbind
of the vectors 1:5
and 5:1
.
如果边缘列表中包含权重,那么您需要一个略有不同的解决方案.
If your edgelist includes weights, then you need a slightly different solution.
el <- cbind(a=1:5, b=5:1, c=c(3,1,2,1,1)) # edgelist (a=origin, b=destination, c=weight)
mat<-matrix(0, 5, 5)
for(i in 1:NROW(el)) mat[ el[i,1], el[i,2] ] <- el[i,3] # SEE UPDATE
mat
# [,1] [,2] [,3] [,4] [,5]
#[1,] 0 0 0 0 3
#[2,] 0 0 0 1 0
#[3,] 0 0 2 0 0
#[4,] 0 1 0 0 0
#[5,] 1 0 0 0 0
更新
一段时间后,我意识到上一个加权边列表示例中的for循环(第3行)是不必要的.您可以将其替换为以下矢量化操作:
Some time later I realized that the for loop (3rd line) in the previous weighted edgelist example is unnecessary. You can replace it with the following vectorized operation:
mat[el[,1:2]] <- el[,3]
这篇关于如何从边缘列表创建加权邻接表/矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!