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

时间:2019-07-31 08:24:45

标签: r

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

v = c(10,23,25,26,38,50)
c = findClosest(v,3)
c
23 25 26

我尝试使用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);

How to find two closest (nearest) values within a vector in MATLAB?

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

或使其成为一个函数

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

答案 3 :(得分:5)

一个基本的R选项,想法是我们首先对向量进行sort并在排序后的向量中将每个i元素与i + n - 1元素相减,然后选择差异最小的组。 / p>

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

在平局的情况下,由于我们使用的是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  

答案 4 :(得分:0)

要在数据框中使用

data%>%
group_by(var1,var2)%>%
do(data.frame(findClosest(.$val,3)))