R cut() Function - Numeric Binning
The R cut() function is used to divide continuous numeric values into discrete intervals (bins).
Binning is an important step in data preprocessing, often used for creating grouped statistics and histograms.
The syntax of the cut() function is as follows:
cut(x, breaks, labels = NULL, right = TRUE)
Parameter description:
xInput numeric vector.
breaksBreakpoint vector, or the number of desired intervals.
labelsCustom interval labels; by default, interval ranges are used.
rightWhether the intervals are right-closed, default 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 ranges
breaks <- c(0, 60, 70, 80, 90, 100)
labels <- c("Fail", "Pass", "Medium", "Good", "Excellent")
grade <- cut(scores, breaks = breaks, labels = labels)
print("Score binning results:")
result <- data.frame(Scores=scores, Grade= grade)
print(result)
# Count the number of each grade
print("Number in each grade:")
print(table(grade))
scores <- c(45, 55, 62, 78, 85, 92, 70, 88, 95, 60, 82, 73)
# Bin by score ranges
breaks <- c(0, 60, 70, 80, 90, 100)
labels <- c("Fail", "Pass", "Medium", "Good", "Excellent")
grade <- cut(scores, breaks = breaks, labels = labels)
print("Score binning results:")
result <- data.frame(Scores=scores, Grade= grade)
print(result)
# Count the number of each grade
print("Number in each grade:")
print(table(grade))
After executing the above code, the output result 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
Other extensions
R Language Example