在 R 编程中对数值向量进行分箱 - .bincode()函数
R 语言中的.bincode()
函数用于对数字向量进行分箱并返回整数代码以进行分箱。
Syntax:
.bincode(x, breaks, right = TRUE, include.lowest = FALSE)
Parameters:
x: a numeric vector which is to be converted to integer codes by binning.
breaks: a numeric vector of two or more cut points, sorted in increasing order.
right: logical value, indicating if the intervals should be closed on the right (and open on the left) or vice versa.
include.lowest: logical value, indicating if an ‘x[i]’ equal to the lowest (or highest, for right = FALSE) ‘breaks’ value should be included in the first (or last) bin.
示例 1:
# R program to illustrate
# .bincode function
# Initializing a numeric vector which is
# to be converted to integer
# codes by binning
x <- c(0, 0.01, 0.5, 0.99, 1)
# a numeric vector of two or more cut
# points, sorted in increasing order
b <- c(0, 1, 2, 3)
# Calling .bincode() function
.bincode(x, b)
.bincode(x, b, TRUE)
.bincode(x, b, FALSE)
输出:
[1] NA 1 1 1 1
[1] NA 1 1 1 1
[1] 1 1 1 1 2
示例 2:
# R program to illustrate
# .bincode function
# Initializing a numeric vector which is
# to be converted to integer
# codes by binning
x <- c(0, 0.1, 0.2, 0.3, 1)
# a numeric vector of two or more cut
# points, sorted in increasing order
b <- c(0, 1, 2, 3)
# Calling .bincode() function
.bincode(x, b, TRUE, TRUE)
.bincode(x, b, FALSE, TRUE)
输出:
[1] 1 1 1 1 1
[1] 1 1 1 1 2