Take a regular sample
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 type="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.
## S4 method for signature 'SpatRaster' spatSample(x, size, method="random", replace=FALSE, na.rm=FALSE, as.raster=FALSE, as.points=FALSE, values=TRUE, cells=FALSE, xy=FALSE, ext=NULL, warn=TRUE) ## S4 method for signature 'SpatVector' spatSample(x, size, method="random", strata=NULL, chess="") ## S4 method for signature 'SpatExtent' spatSample(x, size, method="random", lonlat)
x |
SpatRaster |
size |
numeric. The sample size. If |
method |
character. Should be "regular" or "random". It can also be "stratified" if |
replace |
logical. If |
na.rm |
logical. If |
as.raster |
logical. If |
as.points |
logical. If |
values |
logical. If |
cells |
logical. If |
xy |
logical. If |
ext |
SpatExtent or NULL to restrict sampling to a a subset of the area of |
warn |
logical. Give a warning if the sample size returned is smaller than requested |
strata |
if not NULL, stratified random sampling is done, taking |
chess |
character. One of "", "white", or "black". For stratified sampling if |
lonlat |
logical. If |
numeric or SpatRaster
f <- system.file("ex/elev.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, values=FALSE)
cells <- as.vector(cells)
v <- r[cells]
xy <- xyFromCell(r, cells)
cbind(xy, v)
# regular
cells <- spatSample(r, 6, "regular", cells=TRUE, values=FALSE)
cells <- as.vector(cells)
v <- r[cells]
xy <- xyFromCell(r, cells)
cbind(xy, v)
## SpatExtent
e <- ext(r)
spatSample(e, 10, "random", lonlat=TRUE)
## SpatVector
f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
#sample geometries
i <- sample(nrow(v), 5)
vv <- v[i,]Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.