R/ordinal_median.R

#' Take the Median of Ordinal Data
#' @description This function is used to take the median of an ordered factor, where the
#' output retains the metadata associated with the factor.
#'
#' @param ordinal_vector The ordered factor data to be processed.
#' @param ... Any additional arguments to be passed directly to the median function.
#'
#' @return Returns a single value representing the median of the input data. However, all
#'         of the metadata around the levels and labeling will be retained.
#' @export
#'
#' @examples
#' x <- ordered(c("a","b","b"), levels=c("a", "b"))
#' ordinal_median(x)
ordinal_median <- function(ordinal_vector, ...) {
  levels <- levels(ordinal_vector)
  median <- median(as.numeric(ordinal_vector), ...)
  if(!is.integer(median))
    median <- floor(median)

  median <- ordered(levels[median], levels=levels)
  return(median)
}
jmiahjones/lunch.time documentation built on May 29, 2019, 1:05 a.m.