median

median is a function that calculates the middle value of a vector of values, when arranged in ascending order.

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 the median of the values in a vector when some of the values are: NA, NaN?

Click to see solution
median(c(3,2,4,5,1,NaN), na.rm=T)
[1] 3
mean(c(3,2,NA,NaN,4,5,1), na.rm=T)
[1] 3

How do I get the median of the values in a vector when there are an even number of values?

Click to see solution

Explanation Source Since this vector has an even number of values (6 in this case), there will be two medians. In this case, the medians are the 3rd and 4th value in ascending order. In situations with multiple medians, the mean of the two medians is taken.

median(c(3,2,4,6,5,1))
[1] 3.5

For this example, the median would be the mean of the 3rd and 4th value in ascending order, which would be (3+4)/2, giving us 3.5 as our median.