R Percentiles
A percentile tells you the value below which a given percentage of observations fall. If your exam score is at the 90th percentile, you scored higher than 90% of the class. The 25th, 50th and 75th percentiles are called quartiles; the 50th percentile is the median.
quantile()
quantile(x, probs) computes percentiles. probs are given as proportions between 0 and 1:
quantile(mtcars$mpg, 0.75)
quantile(mtcars$mpg, c(0.1, 0.5, 0.9))
quantile(mtcars$mpg) # default: min, quartiles, max 75%
22.8
10% 50% 90%
14.34 19.20 30.09
0% 25% 50% 75% 100%
10.400 15.425 19.200 22.800 33.900
So 75% of the cars in mtcars get at most 22.8 miles per gallon, and a quarter get more.
The interquartile range
The distance between the first and third quartile is the interquartile range (IQR), a robust measure of spread that ignores the extremes. Box plots draw exactly this range as the box:
q <- quantile(mtcars$mpg, c(0.25, 0.75))
q
unname(q[2] - q[1])
IQR(mtcars$mpg) 25% 75%
15.425 22.800
[1] 7.375
[1] 7.375
Where does a value rank?
The reverse question, "what percentile is this value?", is answered by the empirical cumulative distribution function ecdf():
pct_rank <- ecdf(mtcars$mpg)
pct_rank(21) # share of cars with mpg <= 21
round(100 * pct_rank(c(15, 25, 30)))[1] 0.625
[1] 19 81 88
Different definitions
There are several ways to compute a percentile when it falls between two observations. R implements nine of them (type = 1 to 9); the default is type 7, which interpolates linearly. Statistics textbooks and other software sometimes use a different type, so small differences are normal:
scores <- c(55, 61, 64, 70, 72, 78, 81, 85, 90, 97)
quantile(scores, 0.3)
quantile(scores, 0.3, type = 1) # a value that occurs in the data
quantile(scores, 0.3, type = 6) 30%
68.2
30%
64
30%
65.8
Deciles and grouping
Percentiles are handy for splitting data into equal-sized groups, for example into quartiles of fuel economy:
breaks <- quantile(mtcars$mpg, probs = seq(0, 1, 0.25))
mtcars$mpg_group <- cut(mtcars$mpg, breaks = breaks, include.lowest = TRUE,
labels = c("Q1", "Q2", "Q3", "Q4"))
table(mtcars$mpg_group)
tapply(mtcars$hp, mtcars$mpg_group, mean)
Q1 Q2 Q3 Q4
8 9 8 7
Q1 Q2 Q3 Q4
225.62500 163.88889 112.37500 73.57143
The cars in the lowest fuel-economy quartile have by far the most horsepower.
Missing values
As with mean() and median(), use na.rm = TRUE when the data has gaps:
quantile(airquality$Ozone, c(0.05, 0.95), na.rm = TRUE) 5% 95%
7.75 108.50
Test yourself
Which percentile is the median?
- 25th
- 50th
- 75th
- 100th
How do you compute the 90th percentile of x?
- quantile(x, 90)
- quantile(x, 0.9)
- percentile(x, 90)
- max(x) * 0.9
What does IQR(x) measure?
- The range from min to max
- The spread of the middle 50% of the data
- The mean of the quartiles
- The number of outliers