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 [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 1:length(x)) {
    if (i == 1) {
      climate_spatraster <- subset(x[[i]], time_index)
    } else {
      terra::add(climate_spatraster) <- subset(x[[i]], time_index)
    }
  }
  names(climate_spatraster) <- varnames(climate_spatraster) #<- names(x)
  return(climate_spatraster)
}
EvolEcolGroup/pastclim documentation built on Nov. 6, 2023, 5:11 a.m.