## 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

(medianx,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.

### Simple Example with median() function applied on numeric vector

x = c(1,4,7,9,6) xm = median(x) c(xm) |

[1] 6 |

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

### Example with na.rm=TRUE in median() function applied on numeric vector

x = c(1,4,7,NA,9,6) xm = median(x,na.rm=TRUE) c(xm) |

[1] 6 |

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

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

### Example with na.rm=FALSE in median() function applied on numeric vector

x = c(1,4,7,NA,9,6) xm = median(x,na.rm=FALSE) c(xm) |

[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.

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.