Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I color nodes and edges from an adjacency matrix in r?

Tags:

r

igraph

I have two adjacency matrices of a dynamic network in text files, period 1 and 2 in R (igraph). I'd like to color the vertices and edges that are new in the second network in green.

For example the first network could look like this:

    1   3   6   10  11 
1   NA  NA  NA  NA  NA

3   NA  NA  NA  NA  NA

6   NA  NA  NA  8.695652174 13.04347826

10  NA  NA  2.586206897 NA  3.448275862

11  NA  NA  NA  2.919708029 NA

and changes then to this second network:

    1   2   3   6   10
1   NA  NA  NA  NA  NA

2   NA  NA  NA  NA  NA

3   NA  NA  NA  NA  NA

6   NA  NA  NA  12.32091691 8.022922636

10  NA  NA  7.228915663 NA  NA

The code to read in R:

t1 <- structure(matrix(c(NA,NA,NA,NA,NA, 
                         NA,NA,NA,NA,NA, 
                         NA,NA,NA,8.695652174,13.04347826, 
                         NA,NA,2.586206897,NA,3.448275862,
                         NA,NA,NA,2.919708029,NA),nrow=5, ncol=5, byrow=TRUE),
                dimnames=list(c(1,3,6,10,11), c(1,3,6,10,11)))

t2 <- structure(matrix(c(NA,NA,NA,NA,NA, 
                         NA,NA,NA,NA,NA, 
                         NA,NA,NA,NA,NA, 
                         NA,NA,12.32091691,8.022922636,NA, 
                         NA,NA,7.228915663,NA,NA),nrow=5, ncol=5, byrow=TRUE),
                dimnames=list(c(1,2,3,6,10), c(1,2,3,6,10)))

t3 <- structure(matrix(c(NA,NA,NA,NA,NA, NA,NA,7.2289,NA,NA, NA,10.4798,NA,NA,NA, NA,NA,8.1364,NA,3.8762, NA,NA,NA,NA,NA),nrow=5, ncol=5, byrow=TRUE), dimnames=list(c(1,3,4,6,10), c(1,3,4,6,10)))

How can I link those networks in R, so that R knows which vertices are new?

like image 962
user1829340 Avatar asked Nov 16 '12 10:11

user1829340


1 Answers

Ideally the solution would be to call graph.union, but that has some bugs in the current version, so here is a workaround solution.

You are using NA to mark missing edges, which is a bit strange, because NA means that you don't know whether the edge is missing or not. I'll just replace the NAs with zeros.

t1[is.na(t1)] <- 0
t2[is.na(t2)] <- 0

g1 <- graph.adjacency(t1, weighted=TRUE)
g2 <- graph.adjacency(t2, weighted=TRUE)

## Vertices are easy
V(g2)$color <- ifelse(V(g2)$name %in% V(g1)$name, "black", "darkgreen")

## Edges are a bit trickier
el1 <- apply(get.edgelist(g1), 1, paste, collapse="-")
el2 <- apply(get.edgelist(g2), 1, paste, collapse="-")
E(g2)$color <- ifelse(el2 %in% el1, "black", "green")

plot(g2, vertex.label.color="white", vertex.label=V(g2)$name)

enter image description here

like image 146
Gabor Csardi Avatar answered Oct 18 '22 19:10

Gabor Csardi