How to Calculate Median in R

To calculate a median in R, use the built-in median() function. The median() function takes an R object and splits that into two exact parts, and returns a length-one object of the same type as input.


median(x, na.rm = FALSE, …)


x: An object for which a method has been defined or a numeric vector containing the values whose median is computed.

na.rm: A logical value indicates whether NA values should be stripped before the computation proceeds.

…: They are potentially further arguments for methods; not used in the default method.

Return Value

The median() function returns a length-one object of the same type as the input.

Example 1: How to calculate the median of a vector in R

Define a vector with 5 elements and find the median of that vector.

rv <- 1:5


[1] 3

Our vector contains 1, 2, 3, 4, and 5. The total number of elements is 5, the odd number that means the median() function is the middle number, 3, which returns the 3 in the output.

If the number of elements is even then it will calculate the mean of two middle values.

rv <- 1:6


[1] 3.5

Example 2: Finding a median of sorted numbers

To find the median of the sorted numbers and the numbers are not sorted, use the sort() function to sort the vector and then apply the median() function to that vector.

rv <- c(11, 19, 21, 18, 46)
srv <- sort(rv)


[1] 19

In our example, the input vector is unsorted, and to sort the vector in R, use the sort() function.

We used the sort() function to get into ascending order and then applied the median() function, which returns 19 as the median value.

Example 3: Passing the NA parameter

If there are missing values, then the mean() function returns NA.

rv <- c(1, 2, 3, NA, 4, 5)


[1] NA

And it returns NA in the output.

You can exclude missing values by setting na.rm = TRUE.

rv <- c(1, 2, 3, NA, 4, 5)
median(rv, na.rm = TRUE)


[1] 3

The median is known as a robust location estimator since it ignores outliers.

rv <- c(rnorm(900), rnorm(100, sd = 1000))


[1] 0.06709123

Example 4: Calculating the Median by Group in R

To find the median by the group, combine the aggregate function with the median function.

aggregate(iris$Sepal.Length, list(iris$Species), median)


  Group.1      x
1 setosa      5.0
2 versicolor  5.9
3 virginica   6.5

You can also use the built-in ChickWeight dataset and find the group median.


The median is the middle value of a data set that splits it into two halves. To calculate the median in R, you can use the built-in median() function.

See also

Average in R

Square in R

Standard deviation in R

Percentile in R

Sum in R

Leave a Comment