Skip to content
Prev 13979 / 29559 Next

Selecting n cells more then minDist apart

Here is some code that might work using the utterly fabulous raster 
package!

It is inefficient for a large number of points, and at best this 
approach could be described as "kludgy."  I have not thoroughly tested 
this, but it appears to function as expected.  No doubt others can 
suggest efficiencies, or alternate approaches.  Perhaps sampleRegular() 
will work for you.

library(raster)

sampleMinDist <- function(r, n, minDist) {
    pts <- r
    pts[] <- NA
    pts[sampleRandom(pts, size=1, cells=TRUE, na.rm=FALSE)[1]] <- 1
    for (i in 1:(n-1)) {
      repeat {
         repeat {
            rPt <- sampleRandom(pts, size=1, cells=TRUE, na.rm=FALSE)[1]
            if (length(rPt) > 0) break
            }
         if ((distance(pts)[rPt]) >= minDist) break
       }
       pts[rPt] <- 1
    }
    return(list(pts=pts, ptsXY=xyFromCell(pts, which(pts[]==1))))
}

## Example usage for longlat
rLongLat <- raster(nrow=50, ncol=50)
## Select 10 points a minimum of 5000 m apart
myPts <- sampleMinDist(rLongLat, n=10, minDist=5000)
plot(myPts$pts)
myPts$ptsXY

## Example usage for UTM
rUTM <- raster(nrow=50, ncol=50, xmn=0, xmx=50, ymn=0, ymx=50, 
crs="+proj=utm")
## Select 10 points a minimum of 10 m apart
myPts <- sampleMinDist(rUTM, n=10, minDist=10)

Best,
Paul

-- 
Paul Galpern, PhD Candidate
Natural Resources Institute
70 Dysart Road
University of Manitoba
Winnipeg, Manitoba, Canada R3T 2M6
http://borealscape.ca
On 25/01/2012 5:10 AM, Rainer M Krug wrote: