尝试这个:
library(igraph)
data <- read.table(text=
'wayId firstNode endNode
way1 node1 node2
way2 node2 node4
way3 node2 node3
way4 node4 node3
way5 node5 node6
way6 node5 node8
way7 node8 node7'
,header=TRUE,sep=' ')
# I reorder the columns before passing the data.frame to the function,
# because the first 2 columns have to be node from and node to
g <- graph.data.frame(data[,c(2,3,1)],directed=FALSE)
# plot the graph (don't do it if your graph is really big)
plot.igraph(g,vertex.label=V(g)$name,
vertex.size=30,vertex.label.cex=0.7,
vertex.shape='square')
subGraphs <- decompose.graph(g,mode='strong')
for(i in 1:length(subGraphs)){
subGraph <- subGraphs[[i]]
message(paste('Sub graph:',i))
# find vertices having just one connected node
openVertices <- V(subGraph)[sapply(as.vector(V(subGraph)),FUN=function(v){length(E(subGraph)[from(v) | to(v)]) == 1})]
message(paste('Open vertices:',toString(openVertices$name)))
# plot the sub-graph (don't do it if your graph is really big)
plot.igraph(subGraph,vertex.label=V(subGraph)$name,
vertex.size=30,vertex.label.cex=0.7,
vertex.shape='square')
}