R/validate_harmonize_labels.R

Defines functions validate_harmonize_labels

#' Validate value harmonization mappings
#'
#' Check that a harmonization mapping contains character vectors
#' of original and target value labels and a numeric vector of
#' target value codes, all of equal length.
#'
#' @param harmonize_labels A list or data frame containing
#'   `from`, `to`, and `numeric_values` vectors.
#'
#' @return Invisibly returns TRUE if validation succeeds.
#'   Otherwise, raises an informative error.
#'
#' @keywords internal
#' @noRd
validate_harmonize_labels <- function(harmonize_labels) {
  if (!is.list(harmonize_labels)) {
    stop(
      "'harmonize_labels' must be a list or data frame.",
      call. = FALSE
    )
  }

  required_fields <- c("from", "to", "numeric_values")
  missing_fields <- setdiff(required_fields, names(harmonize_labels))

  if (length(missing_fields) > 0L) {
    stop(
      paste0(
        "Missing harmonization mapping fields: ",
        paste(missing_fields, collapse = ", ")
      ),
      call. = FALSE
    )
  }

  if (!is.character(harmonize_labels$from)) {
    stop(
      "'from' must be a character vector.",
      call. = FALSE
    )
  }

  if (!is.character(harmonize_labels$to)) {
    stop(
      "'to' must be a character vector.",
      call. = FALSE
    )
  }

  if (!is.numeric(harmonize_labels$numeric_values)) {
    stop(
      "'numeric_values' must be a numeric vector.",
      call. = FALSE
    )
  }

  mapping_lengths <- lengths(harmonize_labels[required_fields])

  if (length(unique(mapping_lengths)) != 1L) {
    stop(
      "'from', 'to', and 'numeric_values' must be of equal lengths.",
      call. = FALSE
    )
  }

  invisible(TRUE)
}

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.