return index from a vector of the value closest to a given element
one way:
# 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)))
where x
is your vector.
Alternately,
# this one returns the first index, but is SLOW
sort(abs(x-0.4), index.return=T)$ix[1]
You can also use base::findInterval(0.4, x)
I would use which.min
which.min(abs(x-0.4))
This will return the first index of the closest number to 0.4
.