Take a regular sample of a SpatRaster. Either get cell values, or (when as.raster=TRUE
) get a new SpatRaster with the same extent, but fewer cells. Note that, in order to assure regularity when requesting a regular sample, the number of values returned may not be exactly the same as the size
requested.
# S4 method for SpatRaster
spatSample(x, size, method="regular", replace=FALSE, as.raster=FALSE, cells=FALSE, ...)
SpatRaster
numeric. The sample size
character. Should be "regular" or "random"
logical. If TRUE
, sampling is with replacement (if method="random"
logical. If TRUE
, a SpatRaster is returned
logical. If TRUE
, cellnumbers are returned instead of values
additional arguments. None implemented
numeric or SpatRaster
In some cases you may want to know the location of the sampled cells. In that situation you can take a sample of the cell numbers and use extract. See examples.
In stead of spatSample(x, size, method="random")
you can also use the equivalent base method sample(x, size)
. The base method also works for SpatVector
# NOT RUN {
f <- system.file("ex/test.tif", package="terra")
r <- rast(f)
s <- spatSample(r, 10, as.raster=TRUE)
spatSample(r, 10)
spatSample(r, 10, "random")
## if you require cell numbers and/or coordinates
size <- 6
# random cells
cells <- spatSample(r, 6, "random", cells=TRUE)
v <- r[cells]
xy <- xyFromCell(r, cells)
cbind(xy, v)
# regular
cells <- spatSample(r, 6, "regular", cells=TRUE)
v <- r[cells]
xy <- xyFromCell(r, cells)
cbind(xy, v)
# }
Run the code above in your browser using DataLab