[R-sig-Geo] sampling a raster within a polygon

Andy Bunn Andy.Bunn at wwu.edu
Thu Oct 26 17:39:43 CEST 2017

Thanks Mel and Lauren for your replies. Very helpful indeed.

From: "Bacou, Melanie" <mel at mbacou.com>
Reply-To: "mel at mbacou.com" <mel at mbacou.com>
Date: Tuesday, October 24, 2017 at 10:37 AM
To: Andy Bunn <Andy.Bunn at wwu.edu>, R-sig-Geo <r-sig-geo at r-project.org>
Subject: Re: [R-sig-Geo] sampling a raster within a polygon

Sorry the exact code is:

xy.r <- extract(r, xy.sp)
xy.r.sample <- lapply(xy.r, sample, 10)

On 10/24/2017 01:34 PM, Bacou, Melanie wrote:

Simple use `extract()` instead of `mask()`, and then randomly sample cells in each polygon. Should be much faster, e.g.:

xy.r <- extract(r, xy.sp)
xy.r.sample <- lapply(xy.r, sample.int, n=10)
On 10/23/2017 12:57 PM, Andy Bunn wrote:

Hi all, I’ve followed the thread on the updates to raster and would like to acknowledge the wonderful work done by Robert and others in making raster. It is an amazing piece of software. Thanks to all who help people like me do my job using the fruits of your labors!

Anyways, I’m working with some largish rasters and running into a step that is more computationally intensive than I would like. I’m trying to randomly sample a raster within the bounds of a polygon. E.g., in the example below I’d like to apply sampleRandom() on the raster r but constrain the sample to points within the polygons defined by xy.sp.


    xy = cbind(

      x = c(13.4, 13.4, 13.6, 13.6, 13.4),

      y = c(48.9, 49, 49, 48.9, 48.9)


    hole.xy <- cbind(

      x = c(13.5, 13.5, 13.45, 13.45, 13.5),

      y = c(48.98, 48.92, 48.92, 48.98, 48.98)


    xy.sp <- SpatialPolygons(list(


                    Polygon(hole.xy, hole = TRUE)), "1"),

      Polygons(list(Polygon(xy + 0.2),

                    Polygon(xy + 0.35),

                    Polygon(hole.xy + 0.2, hole = TRUE)), "2")


    r <- raster(nrow=100, ncol=100, ext=extent(xy.sp), resolution=0.01)

    r[] <- runif(ncell(r))



I can accomplish this with a mask  via:

    sampleRandom(mask(r, xy.sp),size = 10)

However, I have many different polygons to apply over a big raster and the mask() is taking a long time. Is there a better way to go about this?

Thanks in advance, A


R-sig-Geo mailing list

R-sig-Geo at r-project.org<mailto:R-sig-Geo at r-project.org>


	[[alternative HTML version deleted]]

More information about the R-sig-Geo mailing list