R/validate_survey_list.R

Defines functions validate_survey_list

#' Validate a list of survey objects
#'
#' Check that a survey list contains valid survey objects with
#' non-missing, unique survey identifiers and filenames.
#'
#' @param survey_list A list of survey or survey_df objects,
#'   or a single survey object.
#'
#' @return Invisibly returns TRUE if validation succeeds.
#'   Otherwise, raises an informative error.
#'
#' @keywords internal
#' @noRd
validate_survey_list <- function(survey_list) {
  if (is.null(survey_list)) {
    stop("The parameter 'survey_list' is NULL.", call. = FALSE)
  }

  if (is.survey(survey_list)) {
    return(invisible(TRUE))
  }

  if (!is.list(survey_list) || is.data.frame(survey_list)) {
    stop(
      "The parameter 'survey_list' is not a list or a single survey.",
      call. = FALSE
    )
  }

  # Validate survey classes.
  valid_surveys <- vapply(survey_list, is.survey, logical(1))

  if (!all(valid_surveys)) {
    stop(
      paste0(
        paste(which(!valid_surveys), collapse = ", "),
        " in 'survey_list' are not surveys."
      ),
      call. = FALSE
    )
  }

  # Extract attributes without premature type coercion.
  ids <- lapply(survey_list, survey_id)

  filenames <- lapply(
    survey_list,
    function(x) attr(x, "filename", exact = TRUE)
  )

  # Validate identifiers and filenames before checking uniqueness.
  valid_scalar <- function(x) {
    is.character(x) &&
      length(x) == 1L &&
      !is.na(x) &&
      nzchar(x)
  }

  valid_ids <- vapply(ids, valid_scalar, logical(1))
  valid_filenames <- vapply(filenames, valid_scalar, logical(1))

  if (!all(valid_ids)) {
    stop(
      paste0(
        "Invalid or missing survey ID at position(s): ",
        paste(which(!valid_ids), collapse = ", ")
      ),
      call. = FALSE
    )
  }

  if (!all(valid_filenames)) {
    stop(
      paste0(
        "Invalid or missing filename at position(s): ",
        paste(which(!valid_filenames), collapse = ", ")
      ),
      call. = FALSE
    )
  }

  # Check uniqueness.
  ids <- unlist(ids, use.names = FALSE)
  filenames <- unlist(filenames, use.names = FALSE)

  duplicate_ids <- unique(ids[duplicated(ids)])
  duplicate_filenames <- unique(filenames[duplicated(filenames)])

  if (length(duplicate_ids) > 0L) {
    stop(
      paste0(
        "Survey IDs are not unique: ",
        paste(duplicate_ids, collapse = ", ")
      ),
      call. = FALSE
    )
  }

  if (length(duplicate_filenames) > 0L) {
    stop(
      paste0(
        "Survey filenames are not unique: ",
        paste(duplicate_filenames, collapse = ", ")
      ),
      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.