R/utils-validate.R

Defines functions .detect_doc_type .validate_df

#' Validate data frame input
#'
#' Internal helper to validate that input is a non-empty data frame
#' and that specified columns exist.
#'
#' @param df Input to validate
#' @param ... Column names (as strings) to check for existence
#' @return Invisible TRUE if valid; throws informative error otherwise
#' @noRd
.validate_df <- function(df, ...) {
  df_name <- deparse(substitute(df))

  if (!is.data.frame(df)) {
    stop("`", df_name, "` must be a data frame, tibble, or data.table. ",
         "Got: ", class(df)[1], call. = FALSE)
  }

  if (nrow(df) == 0L) {
    stop("`", df_name, "` has 0 rows.", call. = FALSE)
  }

  cols <- c(...)
  if (length(cols) > 0L) {
    missing_cols <- setdiff(cols, colnames(df))
    if (length(missing_cols) > 0L) {
      stop("Column(s) not found in `", df_name, "`: ",
           paste(missing_cols, collapse = ", "), ". ",
           "Available columns: ", paste(colnames(df), collapse = ", "),
           call. = FALSE)
    }
  }

  invisible(TRUE)
}

#' Detect output document type
#'
#' Internal helper to detect whether we are rendering to HTML, PDF, Word, or PPTX.
#' Used by table functions to choose kableExtra vs flextable output.
#'
#' @return Character: one of "html", "latex", "docx", "pptx"
#' @noRd
.detect_doc_type <- function() {
  pandoc_to <- knitr::opts_knit$get("rmarkdown.pandoc.to")
  if (!is.null(pandoc_to)) {
    if (pandoc_to %in% c("html", "html4", "html5")) return("html")
    if (pandoc_to %in% c("latex", "beamer")) return("latex")
    if (pandoc_to == "docx") return("docx")
    if (pandoc_to == "pptx") return("pptx")
    return(pandoc_to)
  }
  if (knitr::is_latex_output()) return("latex")
  if (knitr::is_html_output()) return("html")
  "html"
}

Try the Rbearcat package in your browser

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

Rbearcat documentation built on March 21, 2026, 5:07 p.m.