Find the nearest smaller quantity
have a vector with the following number
f<-c(1,3,6,8,10,12,19,27)
this element is closest to 18. So 19 will be the closest element, but the function will need to return 6 (which means the value 12), because the element in the vector must always be less if it is not equal to the input. If the input is 19, then the output should be 7 (index) ...
+3
source to share
7 replies
There is findInterval
:
findInterval(18:19, f)
#[1] 6 7
And let's build a more specific function:
ff = function(x, table)
{
ot = order(table)
ans = findInterval(x, table[ot])
ot[ifelse(ans == 0, NA, ans)]
}
set.seed(007); sf = sample(f)
sf
#[1] 27 6 1 12 10 19 8 3
ff(c(0, 1, 18, 19, 28), sf)
#[1] NA 3 4 6 1
0
source to share