Last active
February 21, 2023 15:27
-
-
Save dgrapov/31f57ddaf03088864df7 to your computer and use it in GitHub Desktop.
Convert adjacency (or other) matrix to edge list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(reshape2) | |
gen.mat.to.edge.list<-function(mat,symmetric=TRUE,diagonal=FALSE,text=FALSE){ | |
#create edge list from matrix | |
# if symmetric duplicates are removed | |
mat<-as.matrix(mat) | |
id<-is.na(mat) # used to allow missing | |
mat[id]<-"nna" | |
if(symmetric){mat[lower.tri(mat)]<-"na"} # use to allow missing values | |
if(!diagonal){diag(mat)<-"na"} | |
obj<-melt(mat) | |
colnames(obj)<-c("source","target","value") | |
obj<-obj[!obj$value=="na",] | |
obj$value[obj$value=="nna"]<-NA | |
if(!text){obj$value<-as.numeric(as.character(obj$value))} | |
return(obj) | |
# remove duplicates | |
} | |
#example | |
R-3.1.2> x<-matrix(1:6,3,3) | |
R-3.1.2> x | |
[,1] [,2] [,3] | |
[1,] 1 4 1 | |
[2,] 2 5 2 | |
[3,] 3 6 3 | |
#if matrix is symmetric it extracts one of the triangles (here top) | |
R-3.1.2> gen.mat.to.edge.list(x) | |
source target value | |
4 1 2 4 | |
7 1 3 1 | |
8 2 3 2 | |
If not symmetric and you want diagonal then do the following: | |
R-3.1.2> gen.mat.to.edge.list(x,symmetric=FALSE,diagonal = TRUE) | |
source target value | |
1 1 1 1 | |
2 2 1 2 | |
3 3 1 3 | |
4 1 2 4 | |
5 2 2 5 | |
6 3 2 6 | |
7 1 3 1 | |
8 2 3 2 | |
9 3 3 3 | |
#with mising values present | |
R-3.1.2> x[sample(1:6,3)]<-NA | |
R-3.1.2> x | |
[,1] [,2] [,3] | |
[1,] 1 NA 1 | |
[2,] 2 5 2 | |
[3,] NA NA 3 | |
R-3.1.2> gen.mat.to.edge.list(x,symmetric=FALSE,diagonal = TRUE) | |
source target value | |
1 1 1 1 | |
2 2 1 2 | |
3 3 1 NA | |
4 1 2 NA | |
5 2 2 5 | |
6 3 2 NA | |
7 1 3 1 | |
8 2 3 2 | |
9 3 3 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment