Skip to contents

This function extracts values from a raster layer (r) over a spatial object (x). If the spatial object contains multiple z indices (e.g. time), then spatial extractions for each time will be returned. It also ensures that the extraction does not exceed available RAM. If the raster is too large, the function can chunk the raster into smaller pieces and process each chunk sequentially to avoid memory overflow.

Usage

extract_over_space(
  x,
  r,
  spatial_fun = mean,
  na.rm = TRUE,
  chunk = TRUE,
  max_ram_frac_per_chunk = 1,
  extraction_fun = terra::extract,
  scale = NULL,
  verbose = TRUE,
  ...
)

Arguments

x

An sf spatial object, representing the locations over which raster values need to be extracted.

r

A terra::SpatRaster object, representing the raster layer from which values need to be extracted.

spatial_fun

Function used to summarise multiple values within a polygon or line. Is passed to extraction_fun internally. Defaults to mean.

na.rm

Whether to remove NA values when summarising with the spatial_fun function.

chunk

Logical. If TRUE, the raster will be split into chunks based on available RAM and processed chunk by chunk. If FALSE, the raster will be processed as a whole. Default is TRUE.

max_ram_frac_per_chunk

The maximum fraction of available memory to use for each extraction chunk.

extraction_fun

The extraction function to use. Default is terra::extract.

scale

The scale to aggregate your raster to (in units of the original raster). Note this will be rounded to fit the nearest aggregation factor (number of cells in each direction). Leave as NULL (the default) if you do not want any aggregation. See aggregate.

verbose

Whether to print messages to the console. Defaults to TRUE.

...

Additional arguments to pass to terra::extract.

Value

A matrix or list where each column corresponds to a raster layer and each row corresponds to a geometry in x. The values represent the raster values at each point's location.

Details

This function uses the terra::mem_info function to assess the RAM requirements for the extraction. If chunking is required (i.e., the raster data does not fit in available RAM), the raster is divided into a number of chunks such that each chunk's RAM requirement does not exceed the available RAM. The function then processes each chunk sequentially, extracting the raster values over the spatial object, and combines the results at the end. Progress of the extraction is displayed.

Examples

# Assuming 'some_raster' is a terra::SpatRaster object and 'some_sp' is a
# spatial object:
# result <- extract_over_space(x=some_sp, r=some_raster)