Calculate median of a vector in R

In this tutorial, we shall learn to calculate median of a vector in R

Median of a vector

Median of a vector is the central tendency of elements in the vector. Median is calculated by arranging items of a vector in ascending and descending order, and the item that is in the middle of the sorted vector is our median. A built-in function called median() is used to calculate median of a vector in R programming language.

Syntax of median() in R

The syntax of median() function is

</>
Copy
median(x, na.rm = FALSE, ...)

where

  • x could be numeric vector.
  • na.rm mean NA ReMoval. It could be TRUE or FALSE. If TRUE, NA values in vector would be stripped out before median computation proceeds.

Examples to Calculate median of a vector in R

We shall learn to calculate median with different options available with median() function.

Example 1 – median() of Numeric Vector

In this example, we will take a numeric vector and find its median using median() function.

example.R – R Program

</>
Copy
x = c(1,4,7,9,6)
xm = median(x)
c(xm)

Output

[1] 6

Explanation

xm = median(1,4,7,9,6) = center_element(1,4,6,7,9) = 6

Example 2 – median() of Numeric Vector with na.rm=TRUE

In this example, we will take a numeric vector and find its median using median() function.

example.R – R Program

</>
Copy
x = c(1,4,7,NA,9,6)
xm = median(x,na.rm=TRUE)
c(xm)

Output

[1] 6

na.rm = TRUE removes all the NA values present in vector before calculation proceeds.

Explanation

xm = median(1,4,7,NA,9,6) = center_element(1,4,6,7,9) = 6

Example 3 – median() of Numeric Vector with na.rm=FALSE

In this example, we will take a numeric vector and find its median using median() function.

example.R – R Program

</>
Copy
x = c(1,4,7,NA,9,6)
xm = median(x,na.rm=FALSE)
c(xm)

Output

[1] NA

na.rm = FALSE does not remove NA values present in vector before calculation proceeds. And if NA is present in the vector, median would be NA irrespective of anything else.

Explanation

xm = median(1,4,7,NA,9,6) = NA

If NA s are expected in a vector, na.rm has to be considered.

Conclusion

In this R Tutorial, we have learnt about median() function and how to Calculate Median of a Vector in R with Example R Scripts.