Biocodenv Blog Bioinformatics, Code, Stuff

3Oct/102

R + igraph: Removing nodes that lack edges

A problem that has been vexing me for awhile is:

How do I get rid of nodes that don't have edges before I send it to Cytoscape?!

Well, it turns out it's rather simple:

> new_g <- delete.vertices(g, which(degree(g) < 1)-1)

Here we're assuming the original graph is called g. The which function returns the elements where the degree of the vertex is less than 1.  igraph numbers its vertices starting at 0, while R numbers its vertex indices at 1, thus the index from the which function has to be subtracted by 1.

If you want proof that this works:

> g <- erdos.renyi.game(1000, 10/1000)

> g <- add.vertices(g, nv=1)

> V(g)

> degree(g)

> g2 <- delete.vertices(g, which(degree(g) < 1)-1)

> V(g2)

> degree(g)

Q.E.D. -- more or less.

22Jan/100

R Recipe: Repeating Columns in a Matrix using R

Someone recently asked me how to repeat a column in a matrix or dataframe using R. It's actually amazingly simple:

> x <- c(1,2,3,4,5)
> mx <- as.matrix(x)  #this part is crucial
> y <- mx[,rep(1,10)]  #this will repeat column 1 ten times
> y
    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    1    1    1    1    1    1    1    1     1
[2,]    2    2    2    2    2    2    2    2    2     2
[3,]    3    3    3    3    3    3    3    3    3     3
[4,]    4    4    4    4    4    4    4    4    4     4
[5,]    5    5    5    5    5    5    5    5    5     5