R/slice_region_series.R

Defines functions slice_region_series

Documented in slice_region_series

#' Extract a slice for a time series of climate variables for a region
#'
#' This function extracts a time slice from time series of one or more climate
#' variables for a given dataset covering a region (or the whole world).
#'
#' @param x climate time series generated with [region_series()]
#' @param time_bp time slice in years before present (i.e. 1950, negative
#'   integers for values in the past). The slices need to exist in the dataset.
#'   To check which slices are available, you can use `time_bp(x)`.
#' @param time_ce time slice in years CE. Only one of `time_bp` or `time_ce`
#'   should be used.
#' @returns a [`terra::SpatRaster`] of the relevant slice.
#'
#' @export

slice_region_series <- function(x, time_bp = NULL, time_ce = NULL) {
  time_bp <- check_time_vars(
    time_bp = time_bp, time_ce = time_ce,
    allow_null = FALSE
  )
  if (length(time_bp) != 1) {
    stop("time_bp should be a single time step")
  }
  if (!is_region_series(x)) {
    stop("x is not a valid object generated by region_series")
  }
  # check that time_bp is part of the series
  if (!time_bp %in% time_bp(x[[1]])) {
    stop("time_bp is not a time slice within the region series x")
  }
  # get index
  time_index <- which(time_bp(x[[1]]) == time_bp)
  # now slice it and convert it to a SpatRaster
  for (i in seq_along(x)) {
    if (i == 1) {
      climate_spatraster <- subset(x[[i]], time_index)
    } else {
      terra::add(climate_spatraster) <- subset(x[[i]], time_index)
    }
  }
  # fix the names of the new raster based on the original names of the datasets
  names(climate_spatraster) <- varnames(climate_spatraster) <- names(x)

  return(climate_spatraster)
}

Try the pastclim package in your browser

Any scripts or data that you put into this service are public.

pastclim documentation built on April 3, 2025, 11:18 p.m.