Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 413
user1787675 Avatar asked Nov 02 '12 22:11

user1787675


People also ask

What is edge list data structure?

An edge list is a data structure used to represent a graph as a list of its edges. An (unweighted) edge is defined by its start and end vertex, so each edge may be represented by two numbers. The entire edge list may be represented as a two-column matrix.

What is an edge list Python?

Edge lists One simple representation is just a Python list of m edges, which we call an edge list. To represent an edge, we just give the numbers of the two vertices it's incident on. Each edge in the list is either a Python list with two vertex numbers or a tuple comprising two vertex numbers.


2 Answers

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

like image 108
flodel Avatar answered Oct 07 '22 03:10

flodel


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
like image 40
Zhilong Jia Avatar answered Oct 07 '22 02:10

Zhilong Jia