R/utils_type.R

Defines functions make_support detect_type

Documented in detect_type make_support

#' Detect variable type for JSD
#'
#' @param x First vector.
#' @param y Second vector.
#' @param discrete_max_unique Maximum number of unique values for integer-like
#'   numeric data to be treated as discrete.
#' @param tol Tolerance for integer-like detection.
#'
#' @return One of "continuous" or "discrete".
#' @keywords internal
detect_type <- function(x, y, discrete_max_unique = 10, tol = 1e-8) {
  z <- c(x, y)

  if (is.factor(z) || is.character(z) || is.logical(z)) {
    return("discrete")
  }

  if (!is.numeric(z)) {
    return("discrete")
  }

  z <- z[is.finite(z)]
  if (length(z) == 0) {
    stop("No valid observations available to detect type.")
  }

  unique_n <- length(unique(z))
  integer_like <- all(abs(z - round(z)) < tol)

  if (integer_like && unique_n <= discrete_max_unique) {
    return("discrete")
  }

  "continuous"
}


#' Build support for discrete variables
#'
#' @param x First vector.
#' @param y Second vector.
#' @param support Optional user-specified support.
#'
#' @return A character vector of support values.
#' @keywords internal
make_support <- function(x, y, support = NULL) {
  if (!is.null(support)) {
    return(as.character(support))
  }

  z <- c(x, y)

  if (is.numeric(z)) {
    return(as.character(sort(unique(z))))
  }

  as.character(sort(unique(as.character(z))))
}

Try the jsdtools package in your browser

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

jsdtools documentation built on March 31, 2026, 1:06 a.m.