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

R cut() Function - Numeric Binning

R cut() Function - Numeric Binning

R Language Examples R Language Examples

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:

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

)

print

(

"Score Grading Results:"

)

result

<-

data.frame

(

Score

=

scores, grade

=

grade

)

print

(

result

)

Count the number of each grade

print

(

"Number of People in Each Grade:"

)

print

(

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 R Language Examples