median.factor: Median for ordered factors

View source: R/median.R

median.factorR Documentation

Median for ordered factors

Description

Compute the median of an ordered factor

Usage

## S3 method for class 'factor'
median(x, na.rm = FALSE, ordered_low = FALSE, ...)

Arguments

x

An ordered factor (for unordered factors an error will be thrown).

na.rm

Logical; should NA be removed before computation?

ordered_low

Logical; only used if the length of x is even and the two middle values are unequal (see details).

...

Not used in this function.

Details

Currently, the median for an ordered factor is not implemented in base R. This function is a remedy for this. It allows the computation of “a median” for ordered factors (see below) and overwrites the error message for unordered factors from median.default (hence, the function name is median.factor and not median.ordered).

If the length of x is odd, then the median will be the middle value of the sorted list of elements from x. If the length of x is even and the two middle values of the sorted list of elements from x are equal, then the median is one of these (equal) middle values. The only problematic case is an even length x with unequal middle values. In this case, the median of a numeric vector is normally defined as the mean of the two middle values. However, for ordered factors the mean is not defined. The argument ordered_low cures this problem. If ordered_low = FALSE (the default), then the larger of the two middle values is returned (this value is called ‘hi-median’ in mad). If ordered_low = TRUE, then the smaller of the two middle values is returned (this value is called ‘low-median’ in mad).

Value

a length-one factor

Examples

ord_factor_odd <- ordered(letters[1:5])
median(ord_factor_odd) # calls median.factor, if package is loaded

# If only base R is loaded, median.default will be called
# and will throw an error:
tryCatch(median.default(ord_factor_odd), error = function(e) e)

ord_factor_even <- ordered(letters[1:4])
median(ord_factor_even, ordered_low = FALSE)
median(ord_factor_even, ordered_low = TRUE)

torockel/missMethods documentation built on Sept. 16, 2022, 5:16 p.m.