Remove self loops and vertex with no edges

旧时模样 提交于 2020-02-29 18:15:54

问题


I am constructing a gene network. I have a two column data frame which i converted into and adjacency matrix and use it in igraph. The problem is i have genes that have self loops, I want to get rid of self loops and then get rid of the vertices that have no edge (isolated maybe) from the network. I have tried a few things but somehow they do not work. My code is

 InnatedGraph <- graph.data.frame(innate,directed=FALSE)
 V(InnatedGraph)$label.cex = 0.4
 plot(InnatedGraph,vertex.label=V(InnatedGraph)$symbol, vertex.size=5)

innate is my two column data frame. I have tried the degree function to remove vertices with 0 degree but i guess unfortunately it does not work (maybe becoz the self loop genes have degree 1).

bad.vs<-V(InnatedGraph)[degree(InnatedGraph) == 0] 
clean <-delete.vertices(InnatedGraph, bad.vs)

I tried using another function from package BioNet "rmSelfLoops" with the help of which i was able to remove the self loop edges but then still unable to remove the vertices with no edges.

test<-rmSelfLoops(InnatedGraph)

I will also include a picture of my network just to make it easier to understand.


回答1:


Consider this example graph and its two subsets/modifications:

library(igraph)
set.seed(1)
g <- random.graph.game(10, p.or.m = 3, "gnm") + edge(7,7)
coords <- layout.auto(g)
par(mfrow = c(1,3))
plot(g, layout = coords)
plot(simplify(g), layout = coords) # remove loops and multiple edges
plot(delete.vertices(simplify(g), degree(g)==0)) # additionally delete isolated nodes


Using OP's sample data from the comment:

df <- read.csv(header=F, row.names = 1, stringsAsFactors=F, text='"53","ENSG00000175104","ENSG00000175104"
"54","ENSG00000174775","ENSG00000175104"
"55","ENSG00000032688","ENSG00000027164"
"56","ENSG00000175104","ENSG00000140968"
"57","ENSG00000027164","ENSG00000041515"
"58","ENSG00000027164","ENSG00000025498"')
library(igraph)
( dfclean <- subset(df, V2!=V3) ) # remove rows where source==target
#                V2              V3
# 54 ENSG00000174775 ENSG00000175104
# 55 ENSG00000032688 ENSG00000027164
# 56 ENSG00000175104 ENSG00000140968
# 57 ENSG00000027164 ENSG00000041515
# 58 ENSG00000027164 ENSG00000025498
par(mfrow = c(1,3))
plot(graph_from_data_frame(df), edge.arrow.size = .5) # orig
plot(simplify(graph_from_data_frame(df)), edge.arrow.size = .5) # same as
plot(graph_from_data_frame(dfclean), edge.arrow.size = .5) # this one



回答2:


Use the function graph_from_adjacency_matrix to convert your adjacency matrix into a graph and set the argument diag=F.

That should get rid of the self-loops.



来源:https://stackoverflow.com/questions/40086031/remove-self-loops-and-vertex-with-no-edges

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!