如何找到向量中三个最接近的(最近的)值?

Ter*_*rry 14 r

我想找出向量中三个最接近的数字。就像是

v = c(10,23,25,26,38,50)
c = findClosest(v,3)
c
23 25 26
Run Code Online (Sandbox Code Playgroud)

我尝试使用sort(colSums(as.matrix(dist(x))))[1:3],并且效果不错,但是它选择了具有最小整体距离的三个数字,而不是三个最接近的数字。

matlab已经有一个答案,但是我不知道如何将其转换为R:

%finds the index with the minimal difference in A
minDiffInd = find(abs(diff(A))==min(abs(diff(A))));
%extract this index, and it's neighbor index from A
val1 = A(minDiffInd);
val2 = A(minDiffInd+1);
Run Code Online (Sandbox Code Playgroud)

如何在MATLAB中的向量中找到两个最接近的(最近的)值?

Col*_*ole 11

我的假设是,对于n最接近的值,唯一重要的是之间的差异v[i] - v[i - (n-1)]。也就是说,找到的最小值diff(x, lag = n - 1L)

findClosest <- function(x, n) {
  x <- sort(x)
  x[seq.int(which.min(diff(x, lag = n - 1L)), length.out = n)]
}

findClosest(v, 3L)

[1] 23 25 26
Run Code Online (Sandbox Code Playgroud)


asa*_*ica 6

让我们通过“最小L1距离之和的数字”定义“最近的数字”。您可以结合diff和加窗总和来实现所需的功能。

您可以编写一个简短得多的函数,但我逐步编写了此函数,以使其易于理解。

v <- c(10,23,25,26,38,50)

#' Find the n nearest numbers in a vector
#'
#' @param v Numeric vector
#' @param n Number of nearest numbers to extract
#'
#' @details "Nearest numbers" defined as the numbers which minimise the
#'   within-group sum of L1 distances.
#'   
findClosest <- function(v, n) {
  # Sort and remove NA
  v <- sort(v, na.last = NA)

  # Compute L1 distances between closest points. We know each point is next to
  # its closest neighbour since we sorted.
  delta <- diff(v)

  # Compute sum of L1 distances on a rolling window with n - 1 elements
  # Why n-1 ? Because we are looking at deltas and 2 deltas ~ 3 elements.
  withingroup_distances <- zoo::rollsum(delta, k = n - 1)

  # Now it's simply finding the group with minimum within-group sum
  # And working out the elements
  group_index <- which.min(withingroup_distances)
  element_indices <- group_index + 0:(n-1)

  v[element_indices]
}

findClosest(v, 2)
# 25 26
findClosest(v, 3)
# 23 25 26
Run Code Online (Sandbox Code Playgroud)


Sot*_*tos 5

一个想法是使用zoo库进行滚动操作,即

library(zoo)
m1 <- rollapply(v, 3, by = 1, function(i)c(sum(diff(i)), c(i)))
m1[which.min(m1[, 1]),][-1]
#[1] 23 25 26
Run Code Online (Sandbox Code Playgroud)

或者把它变成一个函数,

findClosest <- function(vec, n) {
    require(zoo)
    vec1 <- sort(vec)
    m1 <- rollapply(vec1, n, by = 1, function(i) c(sum(diff(i)), c(i)))
    return(m1[which.min(m1[, 1]),][-1])
}

findClosest(v, 3)
#[1] 23 25 26
Run Code Online (Sandbox Code Playgroud)


Ron*_*hah 5

一个基本的R选项,即我们首先sort使用向量,然后将每个ith元素与i + n - 1已排序向量中的element 相减,然后选择差异最小的组。

closest_n_vectors <- function(v, n) {
   v1 <- sort(v)
   inds <- which.min(sapply(head(seq_along(v1), -(n - 1)), function(x) 
                     v1[x + n -1] - v1[x]))
   v1[inds: (inds + n - 1)]
}

closest_n_vectors(v, 3)
#[1] 23 25 26

closest_n_vectors(c(2, 10, 1, 20, 4, 5, 23), 2)
#[1] 1 2

closest_n_vectors(c(19, 23, 45, 67, 89, 65, 1), 2)
#[1] 65 67

closest_n_vectors(c(19, 23, 45, 67, 89, 65, 1), 3)
#[1]  1 19 23
Run Code Online (Sandbox Code Playgroud)

如果是平局,这将返回最小值,因为我们正在使用which.min


基准

既然我们有很多答案,那么到目前为止,值得对所有解决方案进行基准测试

set.seed(1234)
x <- sample(100000000, 100000)

identical(findClosest_antoine(x, 3), findClosest_Sotos(x, 3), 
          closest_n_vectors_Ronak(x, 3), findClosest_Cole(x, 3))
#[1] TRUE

microbenchmark::microbenchmark(
    antoine = findClosest_antoine(x, 3),
    Sotos = findClosest_Sotos(x, 3), 
    Ronak  = closest_n_vectors_Ronak(x, 3),
    Cole = findClosest_Cole(x, 3),
    times = 10
)



#Unit: milliseconds
#  expr      min       lq     mean   median       uq      max neval cld
#antoine  148.751  159.071  163.298  162.581  167.365  181.314    10  b 
#  Sotos 1086.098 1349.762 1372.232 1398.211 1453.217 1553.945    10   c
#  Ronak   54.248   56.870   78.886   83.129   94.748  100.299    10 a  
#   Cole    4.958    5.042    6.202    6.047    7.386    7.915    10 a  
Run Code Online (Sandbox Code Playgroud)