Skip to content

Filtering a set of points by minimum distance between them [SUMMARY]

1 message · Arnald Marcer

#
Hi,

I finally figured out how to select a subset of coordinates so that
any given one is at a minimum distance of any other one. Here
is the function I wrote. Roger, pointed me how to do it with the spdep
package but I have not been able to do it. I figured out another way,
surely less general, but which works for projected coordinates only.

Arnald
CREAF

Here it is my solution:
#*************************************************************************
sampleByMinDistance <- function(min.dist=0, coords){

     # shuffle the coordinates to factor in randomness in the selection 
of points
     coords <- coords[sample(1:length(coords[,1]), length(coords[,1])),]

     # initialize vector of indices at index 1 of coordinates
     v <- c(1)
     is.far <- TRUE
     for(i in 1:length(coords[,1])){
         for(j in 1:length(v)){
                 dist <- distance(coords[i,], coords[v[j],])
                 if(dist < min.dist){
                     is.far <- FALSE
                 }
         }
         if(is.far){
             v <- append(v, i)
         }
         is.far <- TRUE
     }
     return(coords[v,)
}
#**************************************************************************
distance <- function(p1, p2){
      dx <- abs(p1[1,1] - p2[1,1])
      dy <- abs(p1[1,2] - p2[1,2])
      dist <- sqrt(dx^2 + dy^2)
      return(dist)
}
#**************************************************************************
On 03/03/2011 10:42 AM, Roger Bivand wrote: