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

Roger Bivand Roger.Bivand at nhh.no
Wed Feb 27 08:56:46 CET 2008


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


>
> 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
>
>
>
>

-- 
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, Helleveien 30, N-5045 Bergen,
Norway. voice: +47 55 95 93 55; fax +47 55 95 95 43
e-mail: Roger.Bivand at nhh.no




More information about the R-sig-Geo mailing list