首先使用变量参数x 启动一个函数,然后是引用table 和n
.nearest_n <- function(x, table, n) {
该算法假定table 是数字,没有任何重复,并且所有值都是有限的; n 必须小于或等于表的长度
## assert & setup
stopifnot(
is.numeric(table), !anyDuplicated(table), all(is.finite(table)),
n <= length(table)
)
对表格进行排序,然后'clamp'最大值和最小值
## sort and clamp
table <- c(-Inf, sort(table), Inf)
len <- length(table)
在table 中找到x 出现的区间; findInterval() 使用高效搜索。使用区间索引作为初始的下索引,并为上索引加 1,确保保持在边界内。
## where to start?
lower <- findInterval(x, table)
upper <- min(lower + 1L, len)
通过比较上下索引距离与x 的距离,找到最近的n 邻居,记录最接近的值,并酌情增加上下索引并确保保持在边界内
## find
nearest <- numeric(n)
for (i in seq_len(n)) {
if (abs(x - table[lower]) < abs(x - table[upper])) {
nearest[i] = table[lower]
lower = max(1L, lower - 1L)
} else {
nearest[i] = table[upper]
upper = min(len, upper + 1L)
}
}
然后返回解并完成函数
nearest
}
代码可能看起来很冗长,但实际上相对高效,因为对整个向量(sort()、findInterval())的唯一操作在 R 中高效实现。
这种方法的一个特别的优点是它可以在它的第一个参数中进行向量化,计算使用 lower (use_lower = ...) 作为向量并使用 pmin() / pmax() 作为钳位的测试。
.nearest_n <- function(x, table, n) {
## assert & setup
stopifnot(
is.numeric(table), !anyDuplicated(table), all(is.finite(table)),
n <= length(table)
)
## sort and clamp
table <- c(-Inf, sort(table), Inf)
len <- length(table)
## where to start?
lower <- findInterval(x, table)
upper <- pmin(lower + 1L, len)
## find
nearest <- matrix(0, nrow = length(x), ncol = n)
for (i in seq_len(n)) {
use_lower <- abs(x - table[lower]) < abs(x - table[upper])
nearest[,i] <- ifelse(use_lower, table[lower], table[upper])
lower[use_lower] <- pmax(1L, lower[use_lower] - 1L)
upper[!use_lower] <- pmin(len, upper[!use_lower] + 1L)
}
# return
nearest
}
例如
> set.seed(123)
> table <- sample(100, 10)
> sort(table)
[1] 5 29 41 42 50 51 79 83 86 91
> .nearest_n(c(30, 20), table, 4)
[,1] [,2] [,3] [,4]
[1,] 29 41 42 50
[2,] 29 5 41 42
通过获取任何参数并使用参考查找表table0 和其中的索引table1 将其强制转换为所需的形式来概括这一点
nearest_n <- function(x, table, n) {
## coerce to common form
table0 <- sort(unique(c(x, table)))
x <- match(x, table0)
table1 <- match(table, table0)
## find nearest
m <- .nearest_n(x, table1, n)
## result in original form
matrix(table0[m], nrow = nrow(m))
}
举个例子……
> set.seed(123)
> table <- sample(c(letters, LETTERS), 30)
> nearest_n(c("M", "Z"), table, 5)
[,1] [,2] [,3] [,4] [,5]
[1,] "o" "L" "O" "l" "P"
[2,] "Z" "z" "Y" "y" "w"