R:找到最近的索引

Mik*_*e T 7 r vectorization nearest-neighbor

我有两个向量,有几千点,但在这里概括:

A <- c(10, 20, 30, 40, 50)
b <- c(13, 17, 20)
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到的indicies A最近b?预期的结果将是c(1, 2, 2).

我知道,findInterval只能找到第一次出现,而不是最近的,而且我知道,which.min(abs(b[2] - A))逐渐回暖,但我无法弄清楚如何向量化它与两个长向量的工作Ab.

Sac*_*amp 12

你可以把你的代码放在一个sapply中.我认为它具有与for循环相同的速度,因此在技术上没有矢量化:

sapply(b,function(x)which.min(abs(x - A)))
Run Code Online (Sandbox Code Playgroud)

  • 请注意`which.min()`仅返回第一个匹配项.可能还有其他元素同样接近. (4认同)

Rob*_*gar 11

FindInterval让你非常接近.你只需要在它返回的偏移和下一个偏移之间进行选择:

#returns the nearest occurence of x in vec
nearest.vec <- function(x, vec)
{
    smallCandidate <- findInterval(x, vec, all.inside=TRUE)
    largeCandidate <- smallCandidate + 1
    #nudge is TRUE if large candidate is nearer, FALSE otherwise
    nudge <- 2 * x > vec[smallCandidate] + vec[largeCandidate]
    return(smallCandidate + nudge)
}

nearest.vec(b,A)
Run Code Online (Sandbox Code Playgroud)

返回(1,2,2),并且在性能上应该与FindInterval相当.