Skip to contents

Return the middle element of an atomic vector after sorting. Missing values are automatically removed.

Usage

middle(x)

Arguments

x

An atomic vector.

Value

A scalar of the same type as x.

Details

For odd-length input, returns the unique middle element of the sorted vector. For even-length input, returns the lower of the two middle elements (sort(x)[ceiling(length(x) / 2)]), not the average. This differs from stats::median() and allows middle() to work on any atomic type, including character and factor inputs.

Examples

#----------------------------------------------------------------------------
# middle() example
#----------------------------------------------------------------------------
library(bkbase)

# Odd-length input returns the single middle element
middle(c(1, 2, 3, 4, 5))
#> [1] 3

# Even-length input returns the lower of the two middle elements
middle(c(1, 2, 3, 4))
#> [1] 2

# Works on any atomic type
middle(c("a", "b", "c", "d", "e"))
#> [1] "c"

# Missing values are removed before selecting the middle element
middle(c(1, 2, 3, NA, NA))
#> [1] 2