本文介绍了从最接近给定元素的值的向量返回索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元素列表,例如

I have a list of elements such as

A=
  0.992688
  0.892195
  0.889151
  0.380672
  0.180576
  0.685028
  0.58195

给定一个输入元素,比如 0.4,我如何找到最接近这个数字的索引.例如,A[4] = 0.380672 最接近 0.4.所以应该回到4

Given an input element, like 0.4, how can I find the index that holds the number being most near to this number. For instance, A[4] = 0.380672 is most near to 0.4. Therefore, it should return to 4

推荐答案

一种方式:

# as mnel points out in his answer, the difference,
# using `which` here gives all indices that match
which(abs(x-0.4) == min(abs(x-0.4)))

其中 x 是您的向量.

或者,

# this one returns the first index, but is SLOW
sort(abs(x-0.4), index.return=T)$ix[1]

这篇关于从最接近给定元素的值的向量返回索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 23:36