Find nearest smaller number

前端 未结 7 1174
粉色の甜心
粉色の甜心 2021-01-18 12:35

I have a vector of numbers

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

I want to compare the values in the vector to another number, and find the c

相关标签:
7条回答
  • 2021-01-18 13:05

    Another one:

    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
    
    0 讨论(0)
提交回复
热议问题