[R-sig-Geo] Shortest distance between points within a polygon

Ruari Rhodes r.rhodes at pgr.reading.ac.uk
Thu Oct 16 12:53:07 CEST 2014


Thanks for the help Robert, Roman and Barry.
Barry's suggestion with gDistance is quite effective; the processing 
time required to rasterize the polygons is a bit of a hinderance, but 
the result is good. If anyone's interested, the code I ended up with 
(based on the shortestPath examples) is as follows:


library(raster)
library(gdistance)

load( '~/poly.RData')
load( '~/pts.RData')

#Create raster from polygon with 0.25 deg resolution
ext <- extent( poly)
r <- raster( ext=ext, resolution=0.25 )
polyRaster <- rasterize( poly, r, field=1, background=-Inf)

#Create transition layer. 1/mean(x) generates a conductance layer.
T <- transition(polyRaster, function(x) 1/mean(x), 8)

#Correct transition layer for geography. "c" indicates "least cost" method.
T <- geoCorrection(T, type="c")

#Find shortest path and output SpatialLines object
sPath1 <- shortestPath(T, pts[1], pts[2], output="SpatialLines")

#Plotting
plot(polyRaster)
points( pts)
lines(sPath1)




*Ruari Rhodes*
PhD Student
/European precipitation accumulation extremes/
Room 1U09 - Dept. of Meteorology
University of Reading,
Earley Gate, Reading, RG6 6BB
r.rhodes at pgr.reading.ac.uk
http://www.met.reading.ac.uk/~jb013101

On 10/13/14 11:54, Ruari Rhodes wrote:
> Hi all,
>
> I need to find the distance between two spatial points which lie within
> a polygon, via the shortest path which lies entirely within the polygon.
> Can anyone suggest a method? I need to find something which requires
> minimal computing resources.
>
> I have some examples of the points and polygons here, both in lonlat format:
> http://www.met.reading.ac.uk/~jb013101/files/R/datasets/poly.RData
> ("poly", a SpatialPolygonsDataFrame)
> http://www.met.reading.ac.uk/~jb013101/files/R/datasets/pts.RData
> ("pts", a SpatialPoints object)
>
> Many thanks for your help.
>

	[[alternative HTML version deleted]]



More information about the R-sig-Geo mailing list