R cut() Function - Numeric Binning
The R cut() function is used to divide continuous values into discrete intervals (binning).
Binning is an important step in data preprocessing, often used to create grouped statistics and histograms.
The syntax of the cut() function is as follows:
cut(x, breaks, labels = NULL, right = TRUE)
Parameter Description:
-
x Input numeric vector.
-
breaks A vector of breakpoints, or the number of intervals desired.
-
labels Custom interval labels, defaulting to the interval ranges.
-
right Whether intervals are right-closed, defaulting to TRUE (left-open, right-closed).
Example
Student scores
scores
<-
c
(
45
,
55
,
62
,
78
,
85
,
92
,
70
,
88
,
95
,
60
,
82
,
73
)
Bin by score range
breaks
<-
c
(
0
,
60
,
70
,
80
,
90
,
100
)
labels
<-
c
(
"Fail"
,
"Pass"
,
"Medium"
,
"Good"
,
"Excellent"
)
grade
<-
cut
(
scores, breaks
=
breaks,
labels
=
labels
)
(
"Score Grading Results:"
)
result
<-
data.frame
(
Score
=
scores, grade
=
grade
)
(
result
)
Count the number of each grade
(
"Number of People in Each Grade:"
)
(
table
(
grade
)
)
The output of the code above is:
[1] "成绩分档结果:"
成绩 等级
1 45 不及格
2 55 不及格
3 62 及格
4 78 中等
5 85 良好
6 92 优秀
7 70 及格
8 88 良好
9 95 优秀
10 60 及格
11 82 良好
12 73 中等
[1] "各等级人数:"
不及格 及格 中等 良好 优秀
2 3 2 3 2
R Language Examples