问题
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