Adjacency matrix in R

只愿长相守 提交于 2020-02-10 09:29:05

问题


I want to find the adjacency matrix from a csv file that includes the information as follows:

A B 
1 2
1 3
1 4
2 5
3 7

and so on. There are 100 nodes but everytime I try to create a matrix and subsequently plot the graph, the error is that it is a non-square matrix. Can somebody help me with the correct code in R?


回答1:


What you have is an edge list. You can build a graph from that and then covert it to an adjacency matrix:

library(igraph)

dat <- read.table(text="A B 
1 2
1 3
1 4
2 5
3 7", header=TRUE)

get.adjacency(graph.edgelist(as.matrix(dat), directed=FALSE))

That gives

7 x 7 sparse Matrix of class "dgCMatrix"

[1,] . 1 1 1 . . .
[2,] 1 . . . 1 . .
[3,] 1 . . . . . 1
[4,] 1 . . . . . .
[5,] . 1 . . . . .
[6,] . . . . . . .
[7,] . . 1 . . . .



回答2:


Maybe something like:

dat <- read.table(text="A B 
1 2
1 3
1 4
2 5
3 7", header=TRUE)

x <- table(dat)
x %*% t(x)

But maybe you actually want: igraph::graph.data.frame



来源:https://stackoverflow.com/questions/21419507/adjacency-matrix-in-r

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