I have a map of London's waterways, which I've grided into a raster dataset to enable me to measure proximity to water from randomly generated points.

What I'd like to do please is to constrain the randomly generated points to a polygon (which represents the sampling area) within the larger grid.

This is the code I've used:

randLocs <- spsample(waterGrid, n=200, type='random')

waterGrid is the overall grid enabling me to measure distances, and I have a polygon which I've loaded as a shapefile.

  • 1
    Put the polygon in as the first argument to spsample rather than the grid.
    – mdsumner
    Mar 9 '15 at 7:33
  • Thanks very much. I've put poly as the first argument: randVals <- spsample(poly,waterGrid,n=606,type="random") but get error message: Error in apply(bb, 1, function(x) diff(range(x))) : dim(X) must have a positive length. Could there be any other possible options? Many thanks
    – Gavin
    Mar 9 '15 at 11:21
  • maybe try spsample(poly,n=606,type="random")? May 24 '15 at 21:40

selecting your randLocs points that intersect with poly is done by

randLocs[poly, ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.