Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R quantile() Function - Computing Quantiles

R quantile() Function - Computing Quantiles

R Language Examples R Language Examples

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

Quantiles are points that divide sorted data into proportions. For example, the median is the 50% quantile.

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

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

Parameter Description:

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 quantiles

print

(

"Custom quantiles (10%, 50%, 90%):"

)

print

(

quantile

(

scores, probs

=

c

(

0.1

,

0.5

,

0.9

)

)

)

The output of the code above 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 distribution characteristics and detect outliers:

Example

Detect outliers using the IQR method

scores

<-

c

(

55

,

62

,

68

,

70

,

72

,

75

,

78

,

80

,

82

,

85

,

120

)

Compute 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 the outliers

outliers

<-

scores

[

scores

<

lower_bound

|

scores

upper_bound

]

print

(

paste

(

"Outliers:"

, outliers

)

)

The output of the code above is:

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

[1] "异常值: 120"

R Language Examples R Language Examples