R median() - Calculating the Median
The R median() function is used to calculate the median of a sample.
The median (Median), also called the middle value, is a statistical term referring to the number at the middle position in a set of data arranged in order. It represents a value of a sample, population, or probability distribution, and can divide 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:
-
x Input vector
-
na.rm A boolean value, default FALSE, sets whether to remove missing values NA from the input vector; TRUE removes NA.
Example
Create a vector
x
<-
c
(
1
,
2
,
3
,
4
,
5
,
6
,
7
)
Calculate the median
result.
median
<-
median
(
x
)
(
result.
median
)
The output of the code above is:
[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 returned result is NA:
Example
Create a vector
x
<-
c
(
1
,
2
,
3
,
4.5
,
6
,NA
)
Compute an average
result.
median
<-
median
(
x
)
(
result.
median
)
Remove NA
result.
median
<-
median
(
x,na.
rm
=
TRUE
)
(
result.
median
)
The output of the code above is:
[1] NA
[1] 3
R Language Examples