How to create an edge list from a matrix in R?

走远了吗. 提交于 2019-11-28 09:17:01
flodel

Using the igraph package:

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.html since a lot of your recent questions are all simple case usages.

(As a bonus, plot(g) will answer your other question How to plot relationships in R?)

using melt in reshape2, and then delete the weight==0. if no need to print the weight. just delete it.

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

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