R:找到最近的索引 [英] R: find nearest index

查看:113
本文介绍了R:找到最近的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个具有几千个点的向量,但是在这里概括如下:

I have two vectors with a few thousand points, but generalized here:

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

如何获得最近bA标记?预期的结果将是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))的温度正在升高,但是我不知道如何将其向量化以用于长向量Ab.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆