spatSample {terra} | R Documentation |
Take a regular sample
Description
Take a spatial sample from a SpatRaster, SpatVector or SpatExtent. Sampling a SpatVector or SpatExtent always returns a SpatVector of points.
With a SpatRaster, you can get cell values, cell numbers (cells=TRUE
), coordinates (xy=TRUE
) or (when method="regular"
and as.raster=TRUE
) get a new SpatRaster with the same extent, but fewer cells.
In order to assure regularity when requesting a regular sample, the number of cells or points returned may not be exactly the same as the size
requested.
Usage
## S4 method for signature 'SpatRaster'
spatSample(x, size, method="random", replace=FALSE, na.rm=FALSE,
as.raster=FALSE, as.df=TRUE, as.points=FALSE, values=TRUE, cells=FALSE,
xy=FALSE, ext=NULL, warn=TRUE, weights=NULL, exp=5, exhaustive=FALSE)
## S4 method for signature 'SpatVector'
spatSample(x, size, method="random", strata=NULL, chess="")
## S4 method for signature 'SpatExtent'
spatSample(x, size, method="random", lonlat, as.points=FALSE)
Arguments
x |
SpatRaster, SpatVector or SpatExtent |
size |
numeric. The sample size. If |
method |
character. Should be "regular" or "random", If |
replace |
logical. If |
na.rm |
logical. If |
as.raster |
logical. If |
as.df |
logical. If |
as.points |
logical. If |
values |
logical. If |
cells |
logical. If |
xy |
logical. If |
ext |
SpatExtent or NULL to restrict sampling to a subset of the area of |
warn |
logical. Give a warning if the sample size returned is smaller than requested |
weights |
SpatRaster. Used to provide weights when |
strata |
if not NULL, stratified random sampling is done, taking |
chess |
character. One of "", "white", or "black". For stratified sampling if |
lonlat |
logical. If |
exp |
numeric >= 1. "Expansion factor" that is multiplied with |
exhaustive |
logical. If |
Value
numeric matrix, data.frame, SpatRaster or SpatVector
Examples
f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)
s <- spatSample(r, 10, as.raster=TRUE)
spatSample(r, 5)
spatSample(r, 5, na.rm=TRUE)
spatSample(r, 5, "regular")
## if you require cell numbers and/or coordinates
size <- 6
spatSample(r, 6, "random", cells=TRUE, xy=TRUE, values=FALSE)
# regular, with values
spatSample(r, 6, "regular", cells=TRUE, xy=TRUE)
# stratified
rr <- rast(ncol=10, nrow=10, names="stratum")
set.seed(1)
values(rr) <- round(runif(ncell(rr), 1, 3))
spatSample(rr, 2, "stratified", xy=TRUE)
s <- spatSample(rr, 5, "stratified", as.points=TRUE)
plot(rr, plg=list(title="raster"))
plot(s, 1, add=TRUE, plg=list(x=185, y=1, title="points"))
## SpatExtent
e <- ext(r)
spatSample(e, 10, "random", lonlat=TRUE)
## SpatVector
f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
# sample the geometries
i <- sample(v, 3)
# sample points in geometries
p <- spatSample(v, 3)