Always picking the middle element of a vector

Viewed 276

I was wondering how to always pick the middle element in a numeric vector that is sorted from smallest to largest?

When the number of elements is even-numbered, then the smaller element of the two middle elements is desired. Here is an example with the desired output.

g1 = c(8,12,16,24)
g2 = c(8,12,16,24,32)
g3 = c(8,12)
g4 = 8

# Desired Output:
g1 = 12; g2 = 16, g3 = 8, g4 = 8
2 Answers

Try with ceiling on the length divided by 2

f1 <- function(vec) vec[ceiling(length(vec)/2)]

-testing

> f1(g1)
[1] 12
> f1(g2)
[1] 16
> f1(g3)
[1] 8
> f1(g4)
[1] 8

This is how they do it in stats:::mean.default, by adding 1L to the length and using modulo 2 for the subsetting.

f2 <- function(x) x[(length(x) + 1L) %/% 2L]
f2(g1)
# [1] 12
f2(g2)
# [1] 16
f2(g3)
# [1] 8
f2(g4)
# [1] 8
Related