R:找到最近的索引 [英] R: find nearest index
问题描述
我有两个具有几千个点的向量,但是在这里概括如下:
I have two vectors with a few thousand points, but generalized here:
A <- c(10, 20, 30, 40, 50)
b <- c(13, 17, 20)
如何获得最近到b
的A
标记?预期的结果将是c(1, 2, 2)
.
How can I get the indicies of A
that are nearest to b
? The expected outcome would be c(1, 2, 2)
.
我知道findInterval
只能找到第一个出现的位置,而不能找到最近的出现,而且我知道which.min(abs(b[2] - A))
的温度正在升高,但是我不知道如何将其向量化以用于长向量A
和b
.
I know that findInterval
can only find the first occurrence, and not the nearest, and I'm aware that which.min(abs(b[2] - A))
is getting warmer, but I can't figure out how to vectorize it to work with long vectors of both A
and b
.
推荐答案
您可以将代码放在一个小应用程序中.我认为它的速度与for循环的速度相同,因此在技术上没有向量化:
You can just put your code in a sapply. I think this has the same speed as a for loop so isn't technically vectorized though:
sapply(b,function(x)which.min(abs(x - A)))
这篇关于R:找到最近的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!