list 如何从R中的矩阵创建边列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13204046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create an edge list from a matrix in R?
提问by user1787675
The relationship is expressed as a matrix x
like this:
该关系表示为如下矩阵x
:
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?
但是这个边列表允许我创建一个网络图吗?
回答by flodel
Using the igraph
package:
使用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"
I would also recommend you spend some time reading the igraph
documentation at http://igraph.sourceforge.net/index.htmlsince a lot of your recent questions are all simple case usages.
我还建议您花一些时间阅读http://igraph.sourceforge.net/index.html 上的igraph
文档,因为您最近的许多问题都是简单的案例用法。
(As a bonus, plot(g)
will answer your other question How to plot relationships in R?)
(作为奖励,plot(g)
将回答您的另一个问题如何在 R 中绘制关系?)
回答by Zhilong Jia
using melt
in reshape2
, and then delete the weight==0. if no need to print the weight. just delete it.
使用melt
in reshape2
,然后删除 weight==0。如果不需要打印重量。只需删除它。
x
sample1 sample2 sample3 sample4
feature1 0 2 1 1
feature2 2 0 1 0
feature3 1 1 0 1
feature4 1 0 1 0
melt(x)
Var1 Var2 value
1 feature1 sample1 0
2 feature2 sample1 2
3 feature3 sample1 1
4 feature4 sample1 1
5 feature1 sample2 2
回答by bnjmn
Try this
尝试这个
M <- matrix( c(0,2,1,1,2,0,1,0,1,1,0,1,1,0,1,0), 4, 4, dimnames=list(c("A","B","C","D"), c("A","B","C","D")))
eList <- NULL
for ( i in 1:nrow(M) ){
for ( j in 1:ncol(M)) {
eList <- c(eList, rep(paste(dimnames(M)[[1]][i], dimnames(M)[[2]][j] ), M[i,j]))
}
}
Output
输出
> eList
[1] "A B" "A B" "A C" "A D" "B A" "B A" "B C" "C A" "C B" "C D" "D A" "D C"