I am trying to sample random points according to 2 conditions:
- in non-NA cells of a raster
- inside the polygons of a shapefile
I tested the terra::spatSample()
function, but I can’t meet the second condition.
Here is a reproducible example:
library(terra)
set.seed(1)
f <- system.file("ex/elev.tif", package="terra")
f <- terra::rast(f)
v <- system.file("ex/lux.shp", package="terra")
v <- vect(v)
v <- subset(v, v$NAME_2 != "Mersch")
test <- crop(f, v, mask = TRUE)
sp <- terra::spatSample(test, 1000, method="random", replace=FALSE, na.rm=TRUE, as.df=TRUE, as.points=TRUE, xy=TRUE, warn=TRUE, weights=NULL)
plot(test)
plot(v, add = TRUE)
plot(sp, add = TRUE)