R/standalone-any_nonNA.R

Defines functions any_nonNA.ZonesSpatRaster any_nonNA.ZonesRaster any_nonNA.SpatRaster any_nonNA.Raster any_nonNA.sf any_nonNA.Spatial any_nonNA.data.frame any_nonNA.matrix any_nonNA.Matrix any_nonNA.factor any_nonNA.character any_nonNA.logical any_nonNA.numeric any_nonNA.default any_nonNA

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

#' Any non-NA?
#'
#' Check if an object has any non-missing (`NA`) values?
#'
#' @param object.
#'
#' @param names `character` vector of column names.
#'
#' @return A `logical` value.
#'
#' @noRd
any_nonNA <- function(x) UseMethod("any_nonNA")

assertthat::on_failure(any_nonNA) <- function(call, env) {
  x <- eval(call$x, envir = env)
  if (inherits(x, c("SpatRaster", "Raster"))) {
    msg <- paste0(
      "{.arg ",
      deparse(call$x),
      "} must not have a layer with only missing ({.val {NA}}) values."
    )
  } else if (inherits(x, c("data.frame", "sf", "Spatial"))) {
    msg <- paste0(
      "{.arg ",
      deparse(call$x),
      "} must not have a column with only missing ({.val {NA}}) values."
    )
  } else {
    msg <- paste0(
      "{.arg ",
      deparse(call$x),
      "} must not have only missing ({.val {NA}}) values."
    )
  }
  msg
}

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

#' @export
any_nonNA.numeric <- function(x) {
  any(!is.na(x))
}

#' @export
any_nonNA.logical <- function(x) {
  any(!is.na(x))
}

#' @export
any_nonNA.character <- function(x) {
  any(!is.na(x))
}

#' @export
any_nonNA.factor <- function(x) {
  any(!is.na(x))
}

#' @export
any_nonNA.Matrix <- function(x) {
  any(!is.na(x@x))
}

#' @export
any_nonNA.matrix <- function(x) {
  any(!is.na(c(x)))
}

#' @export
any_nonNA.data.frame <- function(x) {
  all(vapply(x, any_nonNA, logical(1)))
}

#' @export
any_nonNA.Spatial <- function(x) {
  all(vapply(x@data, any_nonNA, logical(1)))
}

#' @export
any_nonNA.sf <- function(x) {
  all(vapply(sf::st_drop_geometry(x), any_nonNA, logical(1)))
}

#' @export
any_nonNA.Raster <- function(x) {
  any_nonNA(terra::rast(x))
}

#' @export
any_nonNA.SpatRaster <- function(x) {
  all(terra::global(x, "anynotNA")[[1]])
}

#' @export
any_nonNA.ZonesRaster <- function(x) {
  any_nonNA(terra::rast(raster::stack(raster::as.list(x))))
}

#' @export
any_nonNA.ZonesSpatRaster <- function(x) {
  any_nonNA(terra::rast(terra::as.list(x)))
}

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.