How to create a list of edges from a matrix in R?

The ratio is expressed as a matrix x as follows:

  ABCD A 0 2 1 1 B 2 0 1 0 C 1 1 0 1 D 1 0 1 0 

Entries are among the compounds that they have.

Can someone show me how to write it as an extreme list?

I would rather write this as an extreme list:

 AB AB AC AD BC 

But would this extreme list allow me to create a network plot?

+10
source share
3 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 also recommend that you spend some time reading the igraph documentation at http://igraph.sourceforge.net/index.html, as many of your recent questions are related to a simple case.

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

+28
source

using melt in reshape2 , and then remove the weight == 0. if there is 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 
+13
source

try it

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

Exit

 > eList [1] "AB" "AB" "AC" "AD" "BA" "BA" "BC" "CA" "CB" "CD" "DA" "DC" 
0
source

All Articles