如何从 R 中的矩阵创建边列表? [英] How to create an edge list from a matrix in R?
问题描述
关系用矩阵x
表示,如下所示:
The relationship is expressed as a matrix x
like this:
A B C D
A 0 2 1 1
B 2 0 1 0
C 1 1 0 1
D 1 0 1 0
条目是指他们拥有的连接数.
The entries refer to the number of connections they have.
谁能告诉我如何将它写成边缘列表?
Could anyone show me how to write it as an edge list?
我更愿意把它写成一个边列表:
I would prefer to write it as an edge list:
A B
A B
A C
A D
B C
但是这个边列表允许我创建网络图吗?
But would this edge list allow me to create a network plot?
推荐答案
使用 igraph
包:
x <- matrix(c(0,2,1,1,2,0,1,0,1,1,0,1,1,0,1,0), 4, 4)
rownames(x) <- colnames(x) <- LETTERS[1:4]
library(igraph)
g <- graph.adjacency(x)
get.edgelist(g)
# [,1] [,2]
# [1,] "A" "B"
# [2,] "A" "B"
# [3,] "A" "C"
# [4,] "A" "D"
# [5,] "B" "A"
# [6,] "B" "A"
# [7,] "B" "C"
# [8,] "C" "A"
# [9,] "C" "B"
# [10,] "C" "D"
# [11,] "D" "A"
# [12,] "D" "C"
我还建议您花一些时间阅读 http 上的 igraph
文档://igraph.sourceforge.net/index.html 因为你最近的很多问题都是简单的案例用法.
I would also recommend you spend some time reading the igraph
documentation at http://igraph.sourceforge.net/index.html since a lot of your recent questions are all simple case usages.
(作为奖励,plot(g)
将回答您的另一个问题 如何在 R 中绘制关系?)
(As a bonus, plot(g)
will answer your other question How to plot relationships in R?)
这篇关于如何从 R 中的矩阵创建边列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!