R - median() Function
The R median() function is used to calculate the median of a given numeric vector. The syntax for using this function is given below:
Syntax
median(x, na.rm = FALSE)
Parameters
x |
Required. Specify the numeric vector. |
na.rm |
Optional. Specify TRUE to remove NA or NaN values before the computation. Default is FALSE. |
Return Value
Returns the median of x.
Example:
The example below shows the usage of median() function.
v <- c(10, 15, 20, 25, 30, 35) cat("The vector contains:\n") print(v) cat("median of the vector:", median(v), "\n") m <- matrix(c(10, 20, 30, 40, 50, 60), ncol=2) cat("\nThe matrix contains:\n") print(m) cat("median of the matrix:", median(m)) cat("\nmedian along first column of the matrix:", median(m[,1]))
The output of the above code will be:
The vector contains: [1] 10 15 20 25 30 35 median of the vector: 22.5 The matrix contains: [,1] [,2] [1,] 10 40 [2,] 20 50 [3,] 30 60 median of the matrix: 35 median along first column of the matrix: 20
Using na.rm parameter
The na.rm parameter can be set TRUE to remove NA or NaN values before the computation.
Example:
Consider the example below to see the usage of na.rm parameter.
v1 <- c(10, 20, NA) v2 <- c(10, 20, NaN) cat("median of v1:", median(v1), "\n") cat("median after removing NA:", median(v1, na.rm=TRUE), "\n") cat("\nmedian of v2:", median(v2), "\n") cat("median after removing NaN:", median(v2, na.rm=TRUE), "\n")
The output of the above code will be:
median of v1: NA median after removing NA: 15 median of v2: NA median after removing NaN: 15
❮ R Statistical Functions