R median() - Calculate the median
The R median() function is used to calculate the median of a sample.
The median, also called the middle value, is a technical term in statistics. It is the number located in the middle of a set of data arranged in order. It represents a value in a sample, population, or probability distribution, and it divides the set of values into two equal upper and lower parts.
The syntax of the median() function is as follows:
median(x, na.rm = FALSE)
Parameter description:
xInput vector
na.rmBoolean value, default is FALSE, specifies whether to remove missing values NA in the input vector; set to TRUE to remove NA.
Example
x <- c(1, 2, 3, 4, 5, 6, 7)
# Calculate the median
result.median <- median(x)
print(result.median)
Executing the above code produces the following output:
[1] 4
In the input vector of the median function, if an element has no value, it defaults to NA. We can use the third parameter to set whether to remove the default NA values. If NA is not removed, the result returned is NA:
Example
x <- c(1,2,3,4.5,6,NA)
# Calculate the mean
result.median <- median(x)
print(result.median)
# Remove NA
result.median <- median(x,na.rm = TRUE)
print(result.median)
Executing the above code produces the following output:
[1] NA [1] 3Other extensions
R language examples