R/ordinal_median.R

Defines functions ordinal_median

Documented in ordinal_median

#' 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 Dec. 14, 2017, 12:53 p.m.