Learn R Programming

terra (version 0.5-8)

spatSample: Take a regular sample

Description

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.

Usage

# S4 method for SpatRaster
spatSample(x, size, method="regular", replace=FALSE, as.raster=FALSE, cells=FALSE, ...)

Arguments

x

SpatRaster

size

numeric. The sample size

method

character. Should be "regular" or "random"

replace

logical. If TRUE, sampling is with replacement (if method="random"

as.raster

logical. If TRUE, a SpatRaster is returned

cells

logical. If TRUE, cellnumbers are returned instead of values

...

additional arguments. None implemented

Value

numeric or SpatRaster

Details

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.

Examples

Run this code
# NOT RUN {
f <- system.file("exdata/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