[R-sig-Geo] Calculate matrix of distances from points to multiple polygons

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Fri Jan 4 10:43:30 CET 2013


On Thu, Jan 3, 2013 at 9:54 PM, jfeighery <jfeighery at gmail.com> wrote:
> Dear all,I am trying to create a matrix of distances between wells and all
> nearby ponds that will be used to calculate a contamination risk variable
> (the equivalent of Generate Near Table in ArcGIS). The wells locations and
> pond polygons were imported from shapefiles as SpatialPointsDataFrame and
> SpatialPolygonsDataFrame, respectively. Through searching this forum, I
> found solutions that work for two sets of points (e.g. crossdist in
> {spatstat}) or two sets of polygons. The function dist2Line {geosphere}
> works but appears to only find the distance to the nearest polygon. I am
> hoping that there is a way to do this for each polygon without resorting to
> writing a function with a for loop. Thanks in advance for any help or
> advice!John
>

 I think you want gDistance in package:rgeos. If 'ponds' is a
SpatialPolygonsDataFrame with two ponds in it, and pts is a
SpatialPointsDataFrame with 10 wells in it, then:

 > gDistance(ponds,pts,byid=TRUE)
           2         1
1  1.7668458 0.0000000
2  2.2301705 0.0000000
3  2.5487968 0.1181480
4  0.0000000 2.0410047
5  2.6075170 0.0000000
6  1.3145692 0.4563602
7  1.4300834 0.1179114
8  0.0000000 1.0461675
9  0.7633464 0.5052239
10 2.2691795 0.0000000

is all the well-pond nearest distances. Note the zeroes where the well
is inside the pond. I'm not sure what the distance will be if the well
is on an island in a pond...

Once you've got that then its a simple matter to find the nearest. If
you have a massive dataset and really only want to find the nearest
then this procedure might be slow and we'll have to think of something
else...

Barry



More information about the R-sig-Geo mailing list