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

Andy Bunn Andy.Bunn at wwu.edu
Mon Oct 23 18:57:46 CEST 2017


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.


    require(raster)
    
    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(
      Polygons(list(Polygon(xy),
                    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))
    
    plot(xy.sp,col="grey")
    plot(r,add=T,alpha=0.5)



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     




More information about the R-sig-Geo mailing list