[R-sig-Geo] Calculate shortest distance between points belonging to different polygons

Adrian Baddeley adrian.baddeley at uwa.edu.au
Tue Feb 17 15:01:57 CET 2015


Ivan Palmegiani <pan.sapiens.it at gmail.com> writes:

> I'm handling a SpatialPointsDataFrame with 100 ramdom points distributed
> within 13 different polygons.
> 
 > randp
>                      coordinates   Point_ID   Polygon_ ID
> 0  (690926.8, 7522595)         1_hs                    13
> 1  (696727.1, 7576122)         2_hs                      6

> I need to calculate the shortest distance between points belonging to
> different polygons. Basically I'd like to do what nndist {spatstat} does.
> The difference is that the distance should be calculated between
> groups of points instead of within a group of points.

              Well, nndist {spatstat} does that too.

> I tried to use "aggregate" as suggested below but it didn't work out for me.
> http://www.inside-r.org/packages/cran/spatstat/docs/nndist

> Please find my try below:

>  > randp.df<-data.frame(randp)
>  > randp.hs.df
>         Point_ID     coords.x1      coords.x2   Polygon_ ID
> 0            1_hs     690926.8       7522595 13
> 1            2_hs     696727.1       7576122 6
> 2            3_hs     723480.7       7546594 12

> library(spatstat)

> # Calculate nearest neighbors within a polygon
>  > nn.within.pol<-nndist(randp.df[,c(2,3)],by=marks(randp.df$Polygon_ID))

              'marks' is not appropriate here.
              marks() is a function that extracts the marks from a marked point pattern (class 'ppp')
              but you are applying it to a numeric vector. The result is NULL.

              The argument 'by' should be a factor that determines the grouping.

              Just change 'marks' to 'factor' so that the numeric polygon ID will be treated as a factor,

 nn.within.pol<-nndist(randp.df[,c(2,3)],by=factor(randp.df$Polygon_ID))
 
               and proceed as before (also changing the other instances of 'marks' to 'factor')



Adrian Baddeley
spatstat author



More information about the R-sig-Geo mailing list