[R-sig-Geo] select random "blocks" from grid

Dylan Beaudette dylan.beaudette at gmail.com
Wed Feb 27 20:28:51 CET 2008


On Tuesday 26 February 2008, Roger Bivand wrote:
> On Tue, 26 Feb 2008, Dylan Beaudette wrote:
> > Hi,
> >
> > Is there a simple approach to selecting random "blocks" using the sp
> > classes and methods?
> >
> > Say I have a 10x10 grid of polygons, and would like to randomly select 10
> > of these, and save  them to a new sp class (for later saving to GRASS,
> > etc.). Is there a simple approach to this?
> >
> > I have tried something along the lines of accessing the polygons
> > directly:
> >
> > s <- sample(1:100, size=10)
> >
> > # doesn't work
> > grid at polygons[[s]]
>
> library(sp)
> gt <- GridTopology(c(0.5, 0.5), c(1, 1), c(10,10))
> SP <- as(as(SpatialGrid(gt), "SpatialPixels"), "SpatialPolygons")
> class(SP)
> plot(SP, axes=TRUE)
> set.seed(1)
> SP10 <- SP[sample(length(slot(SP, "polygons")), 10)]
> class(SP10)
> plot(SP10, col="green", add=TRUE)
>
> The "[" methods are quite strong.
>
> > # sort of works... but how can I 'upgrade' the result back to a complete
> > set # of polygons which can be saved to GRASS?
> > apply(matrix(s), 1, function(i) grid at polygons[[i]])
> >
> > Ultimately I would like to establish several randomly placed 100m x 100m
> > squares within a square region. Setting up a grid, and selecting random
> > cells seemed like a simple approach, but if there is a better one I would
> > be happy to hear about it!
>
> You could generate points and overlay on the polygons, but you might get
> two points in one polygon.
>
> Hope this helps,
>
> Roger

Thanks for the help Roger.

I was able to accomplish a random selection of grid cells with your examples.

I was also able to create a simple function for randomly generating "blocks" 
of a given size, and distance from each other / edges with some spatstat 
tools [1].

1. http://casoilresource.lawr.ucdavis.edu/drupal/node/551

Cheers,
Dylan

> > I suppose that I could hand-make something that generates random points,
> > expands their geometry to 100x100 meters, and then tests to see if the
> > resulting rectangle falls completely within the region of interest. This
> > would work as a last resort-- surely there must be a cleaner approach
> > within the existing framework (I hope!).
> >
> > Cheers,
> >
> > Dylan



-- 
Dylan Beaudette
Soil Resource Laboratory
http://casoilresource.lawr.ucdavis.edu/
University of California at Davis
530.754.7341




More information about the R-sig-Geo mailing list