R/standalone-get_crs.R

Defines functions get_crs.ZonesSpatRaster get_crs.SpatRaster get_crs.ZonesRaster get_crs.Raster get_crs.Spatial get_crs.sf get_crs.default get_crs

# ---
# repo: prioritizr/prioritizr
# file: standalone-get_crs.R
# imports: [assertthat (>= 0.2.0), cli (>= 3.6.0), sf (>= 1.0-12), terra (>= 1.8-54), raster (>= 3.6.11)]
# ---

#' Get coordinate reference system
#'
#' Extract the coordinate reference system from an object.
#'
#' @param x [sf::st_sf()], [terra::rast()], [Spatial-class], or
#'   [raster::raster()] object.
#'
#' @return A [sf::st_crs()] object.
#'
#' @noRd
NULL

get_crs <- function(x) UseMethod("get_crs")

#' @export
get_crs.default <- function(x) {
  cli::cli_abort("{.arg x} is not a recognized class.")
}

#' @export
get_crs.sf <- function(x) sf::st_crs(x)

#' @export
get_crs.Spatial <- function(x) sf::st_crs(x@proj4string)

#' @export
get_crs.Raster <- function(x) sf::st_crs(raster::crs(x))

#' @export
get_crs.ZonesRaster <- function(x) get_crs(x[[1]])

#' @export
get_crs.SpatRaster <- function(x) {
  x_crs <- terra::crs(x)
  if (nzchar(x_crs)) {
    return(sf::st_crs(x_crs))
  } else {
    return(sf::st_crs(NA))
  }
}

#' @export
get_crs.ZonesSpatRaster <- function(x) get_crs(x[[1]])

na_crs <- "ENGCRS[\"Undefined Cartesian SRS\",\n    EDATUM[\"\"],\n    CS[Cartesian,2],\n        AXIS[\"(E)\",east,\n            ORDER[1],\n            LENGTHUNIT[\"Meter\",1]],\n        AXIS[\"(N)\",north,\n            ORDER[2],\n            LENGTHUNIT[\"Meter\",1]]]"

Try the prioritizr package in your browser

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

prioritizr documentation built on Nov. 10, 2025, 5:07 p.m.