Match values to nearest value in another array in R [duplicate]

狂风中的少年 提交于 2021-02-04 07:31:05

问题


I need to match a value to its nearest corresponding value in R and extract its index.

The command FindInterval(value,array) achieves this but only works if the array is in ascending order.

The command match(value,array) only works if the value provides an exact match to one in the array.

For example,

array <- c(0.1,0.5,0.6,0.3,0.9,1.4,0.45)
value <- 0.47

I'd like a command which then matches this to the nearest corresponding value (here 0.45) and returns the index (here 7).


回答1:


We can subtract value from every element of array , get the absolute difference and get the index position of minimum value using which.min.

which.min(abs(array - value))
# [1] 7


来源:https://stackoverflow.com/questions/45231735/match-values-to-nearest-value-in-another-array-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!