# Median function in R

Median function in R – median() calculates the sample median. The median is the value at the middle when the data is sorted in ascending order. lets see an example of median function with NA and median function of column in dataframe

#### Syntax for median function in R:

median(x, na.rm = FALSE, …)
• x – numeric vector
• rm- whether NA should be removed, if not, NA will be returned

#### Example of Median function in R with odd observation:

```# R median function with 7(odd) observation

x <-c(1.234,2.342,3.4,-4.562,5.671,12.345,-14.567)
median(x)
```

There are 7 observations in above examples. When arranged in ascending order 4th value is the median value so the output will be

 2.342

#### Example of Median function in R with even observation:

```# R median function with 6(even) observation

x <-c(1.234,2.342,-4.562,5.671,12.345,-14.567)
median(x)
```

There are 6 observations in above example. So the median will be average of 3rd and 4th value when arranged in ascending order. So the output will be (1.234+2.342)/2

##### output:
 1.788

Example of Median function in R with NA:

Median function doesn’t give desired output, If NAs are present in the vector. so it has to be handled by using na.rm=TRUE in median() function

```# R median function for input vector which has NA.

x <-c(1.234,2.342,-4.562,5.671,12.345,-14.567,NA)
median(x,na.rm=TRUE)
```
 1.788

#### Example of Median function in R for a column in data frame:

Lets use mtcars data frame to demonstrate R median() function

```# median function for column in data frame

median(mtcars\$mpg)
```
 19.2