R:找到最近的索引

时间:2012-04-15 07:54:36

标签: r vectorization nearest-neighbor

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

A <- c(10, 20, 30, 40, 50)
b <- c(13, 17, 20)

如何才能获得A b的指示?预期结果为c(1, 2, 2)

我知道findInterval只能找到第一个匹配项,而不是最近的那个,我知道which.min(abs(b[2] - A))正在变暖,但我无法弄清楚如何将它矢量化为使用Ab的长向量。

3 个答案:

答案 0 :(得分:11)

您可以将代码放入sapply中。我认为这与for循环具有相同的速度,因此在技术上没有矢量化:

sapply(b,function(x)which.min(abs(x - A)))

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

返回(1,2,2),并且与性能中的FindInterval相当。

答案 2 :(得分:0)

这是一个使用R经常被忽视的outer功能的解决方案。不确定它是否会表现得更好,但确实避免sapply

A <- c(10, 20, 30, 40, 50)
b <- c(13, 17, 20)

dist <- abs(outer(A, b, '-'))
result <- apply(dist, 2, which.min)

# [1] 1 2 2
相关问题