4

I need to convert a shapefile (ESRI) of roads type SpatialLinesDataFrame in a neural network in R.

I do not know how to remove nodes or vertices of the shape. Determine the length of each edge between nodes. With these parameters I can create the network using the packet (network).

Summary: Input shapefile for the igraph network in R.

Thank you from the South of Chile.

Andrie
  • 176,377
  • 47
  • 447
  • 496
  • 3
    I think we could improve the wording here, but it is a reasonable question with a bit of work. Looks like one uber user says no – mdsumner Aug 14 '12 at 00:34
  • Welcome to Stack Overflow! Welcome to StackOverflow. Perhaps if you made a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) that demonstrates your question / problem, people would find it easier to answer. – Andrie Aug 14 '12 at 05:04
  • Agreed on reopen. My guess is "I have a LINE shapefile of connected segments and I want to turn it into a graph network so I can load it into an igraph package object and do shortest-path routing etc on it". The answer then involves building topology from lines and is not trivial... – Spacedman Aug 14 '12 at 07:07
  • We have reopened the question to give you a chance to provide some more information. Please describe your input data in more detail, e.g. by providing the results of `str(x)` or `head(x)`. – Andrie Aug 14 '12 at 07:33
  • 1
    it seems like the inverse of this question http://stackoverflow.com/questions/9205227/output-shapefile-for-the-igraph-network-in-r – agstudy Nov 27 '12 at 05:19

2 Answers2

1

Here is a try --

library(rgdal)
library(igraph)

dsn <- system.file("vectors", package = "rgdal")[1]
sl <- readOGR(dsn=dsn, layer="kiritimati_primary_roads")
lines2xcoord <- function(lns) sapply(lns@Lines, function(l) l@coords[,1])
lines2ycoord <- function(lns) sapply(lns@Lines, function(l) l@coords[,2])

x <- unlist(sapply(sl@lines, lines2xcoord))
y <- unlist(sapply(sl@lines, lines2ycoord))

g <- graph.empty(n=length(x), directed=FALSE)
V(g)$lat <- x
V(g)$lng <- y
e <- c(t(matrix(c(head(V(g),-1),tail(V(g),-1)), ncol=2)))
add.edges(g,e)

Now g is an igraph with the lines. It assumes incorrectly the lines in the shapefile to be connected, though. Also, it does not store lat/lon in this example, but the projected coordinates.

Karsten W.
  • 17,826
  • 11
  • 69
  • 103
1

The shp2graph package can convert SpatialLinesDataFrame objects into igraph objects. Have a look at the nel2igraph function. Here is an example taken from the help file:

data(ORN)
rtNEL<-readshpnw(rn, ELComputed=TRUE)
#Add the edge length as the weight for graph
igr<-nel2igraph(rtNEL[[2]],rtNEL[[3]],weight=rtNEL[[4]])
plot(igr, vertex.label=NA, vertex.size=2,vertex.size2=2)
#plot(rn)

rn is a SpatialLinesDataFrame object that is first converted into a list object, and then converted into an igraph object.

aahr1
  • 11
  • 2