[R-sig-Geo] project2segment -> connecting SpatialLines: some connect, some not
Mathieu Rajerison
mathieu.rajerison at gmail.com
Wed Sep 12 09:23:37 CEST 2012
Hi,
This post could have followed the one about shortest path but I preferred
to make a separate post to make things clearer.
Given a set of points and a set of lines, I tried to make a graph of it.
The operation consisted, firstly, in getting the lines that connect each
point to the nearest point on the segment pattern
For this, I used spatstat::project2segment. spatstat is really a wonderful
package. I think it can be useful for snapping line operations.
I'm stuck because I manage to create some lines between the points and the
segments but some lines connect to the network while others don't.
When they don't, the distance between the end connecting segment point and
the network is extremely small. I put an image of it as attached file.
Here is the code, for those who'd like to give it a try and, eventually,
give an issue. Maybe I did it in a wrong way. It's based on Barry's initial
code.
library(spatstat)
library(rgeos)
library(maptools)
makeNest <- function(n) {
### generate a bunch of SpatialLines on (0,1) square
xy = cbind(runif(n), runif(n), runif(n), runif(n))
lines = Lines(apply(xy, 1, function(z) {
Line(rbind(z[1:2], z[3:4]))
}), ID = 1)
SpatialLines(list(lines))
}
connection2Lines <- function(lines, pts){
sourcePts <- as(pts,"ppp")
projectedPts <- project2segment(sourcePts, as(lines, "psp"))$Xproj
bb <- union.owin(bounding.box(sourcePts), bounding.box(projectedPts))
cnnLines <- as(psp(sourcePts$x, sourcePts$y, projectedPts$x,
projectedPts$y, window=bb), "SpatialLines")
cnnLines <- spChFIDs(cnnLines, sapply(cnnLines at lines, function(x)
paste("connect", x at ID, sep="_")))
proj4string(cnnLines) <- proj4string(lines)
return(cnnLines)
}
n <- 5
pts <- SpatialPoints(cbind(runif(n), runif(n)))
gg = makeNest(10)
cnnLines <- connection2Lines(gg, pts)
plot(gg)
plot(cnnLines, col="red", add=T)
any(gIntersects(cnnLines, gg, byid=TRUE)==FALSE)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://stat.ethz.ch/pipermail/r-sig-geo/attachments/20120912/5d4a7bf0/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: pb.gif
Type: image/gif
Size: 3440 bytes
Desc: not available
URL: <https://stat.ethz.ch/pipermail/r-sig-geo/attachments/20120912/5d4a7bf0/attachment.gif>
More information about the R-sig-Geo
mailing list