As a silly toy example, suppose
x=4.5
w=c(1,2,4,6,7)
I wonder if there is a simple R function that finds the index of the closest match to x
in w
. So if foo
is that function, foo(w,x)
would return 3
. The function match
is the right idea, but seems to apply only for exact matches.
Solutions here (e.g. which.min(abs(w - x))
, which(abs(w-x)==min(abs(w-x)))
, etc.) are all O(n)
instead of log(n)
(I'm assuming that w
is already sorted).
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…