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


I think this answer is pretty simple:



f <- c(1,3,6,8,10,12,19,27)
x <- 18

# find the value that is closest to x
maxless <- max(f[f <= x])
# find out which value that is
which(f == maxless)

      

+7


source


If your vector is f

always sorted you can dosum(f <= x)



f <- c(1,3,6,8,10,12,19,27)

x <- 18
sum(f <= x)
# [1] 6

x <- 19
sum(f <= x)
# [1] 7

      

+4


source


Try this (not a perfect solution)

x<-c(1,3,6,8,10,12,19,27)
showIndex<-function(x,input){
 abs.diff<-abs(x-input)
 index.value<-unique(ifelse(abs.diff==0,which.min(abs.diff),which.min(abs.diff)-1))
return(index.value)
 }
 showIndex(x,12)
    [1] 6
showIndex(x,19)
[1] 7

      

+3


source


You may try:

x <- 18
f <- c(1,3,6,8,10,12,19,27)

ifelse(x %in% f, which(f %in% x), which.min(abs(f - x)) - 1)

      

So, if x

not in f

, it will return the closest previous index. If x

found f

, it will return the index x

.

+2


source


Other:

which.min(abs(18 - replace(f, f>18, Inf)))
#[1] 6

f[which.min(abs(18 - replace(f, f>18, Inf)))]
#[1] 12

      

Or as a function:

minsmaller <- function(x,value) which.min(abs(value - replace(x, x>value, Inf)))
minsmaller(f, 18)
#[1] 6
minsmaller(f, 19)
#[1] 7

      

+2


source


In a functional programming style:

f <- c(1, 3, 6, 8, 10, 12, 19, 27)
x <- 18
Position(function(fi) fi <= x, f, right = TRUE)

      

0


source


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







All Articles