R quantile() Function - Calculating Quantiles

R 语言实例R Language Example

The R quantile() function is used to calculate the quantiles of data.

Quantiles are points that divide data proportionally after sorting. For example, the median is the 50% quantile.

The syntax format of the quantile() function is as follows:

quantile(x, probs = seq(0, 1, 0.25), na.rm = FALSE)

Parameter description:

  • xInput numeric vector.

  • probsQuantile probability values, ranging from 0 to 1. By default, returns quartiles (0, 0.25, 0.5, 0.75, 1).

  • na.rmBoolean value, sets whether to remove missing values NA.

Example

# Create exam scores
scores <- c(55, 62, 68, 70, 72, 75, 78, 80, 82, 85,
            88, 90, 92, 95, 98)

# Default quartiles
print("Quartiles:")
print(quantile(scores))

# Custom quantile points
print("Custom quantile points (10%, 50%, 90%):")
print(quantile(scores, probs = c(0.1, 0.5, 0.9)))

The output of executing the above code is:

[1] "四分位数:"
   0%   25%   50%   75%  100%
55.00 71.00 80.00 88.75 98.00
[1] "自定义分位点 (10%, 50%, 90%):"
 10%  50%  90%
63.2 80.0 94.4

quantile() is often used to identify data distribution characteristics and detect outliers:

Example

# Use the IQR method to detect outliers
scores <- c(55, 62, 68, 70, 72, 75, 78, 80, 82, 85, 120)

# Calculate Q1, Q3, and IQR
Q1 <- quantile(scores, 0.25)
Q3 <- quantile(scores, 0.75)
IQR <- Q3 - Q1

# Outlier boundaries
lower_bound <- Q1 - 1.5 * IQR
upper_bound <- Q3 + 1.5 * IQR
print(paste("Normal range:", round(lower_bound, 1), "to", round(upper_bound, 1)))

# Find outliers
outliers <- scores[scores < lower_bound | scores > upper_bound]
print(paste("Outliers:", outliers))

The output of executing the above code is:

[1] "正常范围: 44.3 到 119.3"
[1] "异常值: 120"

R 语言实例R Language Example

Other Extensions