如何从R中的矩阵创建边列表?

时间:2012-11-02 22:45:46

标签: r list matrix social-networking edge-list

关系表示为矩阵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

条目是指他们拥有的连接数。

有人能告诉我如何把它写成边缘列表吗?

我更愿意把它写成边缘列表:

A B
A B
A C
A D
B C

但是这个边缘列表是否允许我创建网络图?

3 个答案:

答案 0 :(得分:28)

使用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.sourceforge.net/index.html上的igraph文档,因为您最近的许多问题都是简单的案例用法。

(作为奖励,plot(g)将回答您的其他问题How to plot relationships in R?

答案 1 :(得分:13)

melt中使用reshape2,然后删除权重== 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

答案 2 :(得分:0)

试试这个

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]))
  }
}

输出

> 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"