rgeospatialterra

Randomly sample points using polygon's layer bounds in terra


I'm just wondering if there's a way to randomly sample points based on layer bounds similar to QGIS function?

I have a very large raster and a vector consisting of multiple disconnected polygons across an extent. I want to sample random points on the raster ONLY within the layer bounds of the polygons.

I used to do this by clipping the raster using the polygons, but as I am now working with even larger raster, it took too much computing power and not worth to do anymore.

Thanks.


Solution

  • Example data

    library(terra)
    r <- rast(system.file("ex/elev.tif", package="terra"))
    v <- vect(system.file("ex/lux.shp", package="terra"))[c(3,6)]
    

    You can do

    s <- spatSample(v, 20)
    e <- extract(r, s)
    

    See

    plot(r)
    lines(v, lwd=3, col="gray")
    points(s, col="red")