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

前端 未结 3 1540
粉色の甜心
粉色の甜心 2020-12-09 20:00

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             


        
3条回答
  •  感情败类
    2020-12-09 20:35

    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?)

提交回复
热议问题