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

Adrian Baddeley adrian.baddeley at uwa.edu.au
Thu Feb 19 01:53:43 CET 2015


> Thus, my question: is there a way to calculate the distance from each data point and its nearest neighbor (only one) belonging to a different polygon?

OK. First do

      f <- factor(randp.df$Polygon_ID)
      M <-nndist(randp.df[,c(2,3)], by=f)

which is equivalent to what you did before. 
Next in the matrix M we're going to change M[i, Ji] to have the value infinity,
where Ji is the index of the polygon that contains the i-th data point:

     Ji <- as.integer(f)
     ii <- seq_len(nrow(M))
     M[ cbind(ii, Ji) ] <- Inf

Then just take the row-wise minimum

     dmin <- apply(M, 1, min)



Prof Adrian Baddeley FAA
Curtin University
________________________________________
From: Ivan Palmegiani [pan.sapiens.it at gmail.com]
Sent: Wednesday, 18 February 2015 10:11 PM
To: Adrian Baddeley
Cc: r-sig-geo at r-project.org; r.turner at auckland.ac.nz; Ege Rubak
Subject: Re: [R-sig-Geo] Calculate shortest distance between points belonging to different polygons

Dear Adrian,

Thanks for your explanation.

My goal is measuring the minimum distance from each data point to its nearest neighbor belonging to a different polygon (a pair of point then).
In fact, this distance is in the matrix resulting from

> nn.pol<-nndist(randp.df[,c(2,3)], by=factor(randp.df$Polygon_ID)

The polygons I'm considering are relatively small and distant each other so, in my case, the distance between data points belonging to the same polygon is certainly shorter that the distance to data points belonging to other polygons. Thus, the smallest value of each row is the distance from a data point to its nearest neighbor within the same polygon, while the second smallest value of each row is the distance from a data point and its nearest neighbor belonging to another polygon.

The latter value is the distance I want and I extracted it from the matrix using the following for loop:


> min.dist<-NULL

> for(i in 1:nrow(nn.pol)){

+ min.dist.temp<-min(nn.pol[i,] [nn.pol[i,] != min(nn.pol[i,])])

+ min.dist<-as.vector(c(min.dist,min.dist.temp))

+ }

Maybe not the most elegant way to do it...but it worked. The result is a vector whose length is equal to the number of data point.


> head(nn.dist.hs)

[1] 26370.49 15070.99 27587.33 15722.28 15186.39 31147.84

If the polygons were large and tangential or overlapping, I could not know which value I should have extracted because the distance between two points belonging to the same polygon might be larger than the distance between two points belonging to different polygons.

Thus, my question: is there a way to calculate the distance from each data point and its nearest neighbor (only one) belonging to a different polygon?

Regards,

Ivan



More information about the R-sig-Geo mailing list