median

Basics

median is a very simple function that returns the median of a vector of numerical values. The function intrinsically sorts its objects.


Examples

How do I get the median of a vector of values?

Click to see solution
median(c(3,2,4,5,1))
[1] 3

How do I get a vector’s median when some of the values are: NA, NaN?

Click to see solution

See our mean page for information on na.rm.

median(c(3,2,4,5,1,NaN), na.rm=TRUE)
[1] 3
median(c(3,2,NA,NaN,4,5,1), na.rm=TRUE)
[1] 3

How do I get a vector’s median when it has an even number of values?

Click to see solution
median(c(3,2,4,6,5,1))
[1] 3.5

Fortunately, we don’t need to do any extra work here. The vector is sorted, the two middle values are added together, and the resulting number is divided by 2. This copies the manual process we use for finding a median in an even-sized set.