R median() - Calculate Median
The R median() function is used to calculate the median of a sample.
The median, also known as the middle value, is a specialized term in statistics. It is the number located at the midpoint of a sorted set of data, representing a value in a sample, population, or probability distribution that divides the dataset into equal upper and lower halves.
The syntax for the median() function is as follows:
median(x, na.rm = FALSE)
Parameter Description:
- x Input vector
- na.rm Boolean value, default is FALSE. It specifies whether to remove missing values (NA) from the input vector. Setting it to TRUE removes NA.
Example
# Create a vector
x <- c(1, 2, 3, 4, 5, 6, 7)
# Calculate the median
result.median <- median(x)
print(result.median)
Executing the above code outputs:
[1] 4
In the median function, if an element of the input vector is missing, it defaults to NA. We can control the removal of default NA values through the third parameter. If NA is not removed, the result is NA:
Example
# Create a vector
x <- c(1, 2, 3, 4.5, 6, NA)
# Calculate the median
result.median <- median(x)
print(result.median)
# Remove NA
result.median <- median(x, na.rm = TRUE)
print(result.median)
Executing the above code outputs:
[1] NA
[1] 3