R/remove_na_range.R

Defines functions remove_na_range

#' Remove an unused missing value range
#'
#' Remove the SPSS-style missing value range only when no
#' underlying observations fall within its inclusive bounds.
#' Preserve the observation values and all other attributes.
#'
#' @param x A labelled_spss_survey vector.
#'
#' @return A labelled_spss_survey vector, with its missing
#'   value range removed if unused.
#' @keywords internal
#' @noRd
remove_na_range <- function(x) {
  if (!is.labelled_spss_survey(x)) {
    stop(
      "'x' must be a labelled_spss_survey vector.",
      call. = FALSE
    )
  }

  na_range <- labelled::na_range(x)

  if (is.null(na_range)) {
    return(x)
  }

  values <- vctrs::vec_data(x)

  has_missing_values <- any(
    values >= min(na_range) &
      values <= max(na_range),
    na.rm = TRUE
  )

  if (!has_missing_values) {
    attr(x, "na_range") <- NULL
  }

  x
}

Try the retroharmonize package in your browser

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

retroharmonize documentation built on Nov. 29, 2026, 5:06 p.m.