Find nearest smaller number

前端 未结 7 1302
粉色の甜心
粉色の甜心 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 12:55

    There is findInterval:

    findInterval(18:19, f)
    #[1] 6 7
    

    And building a more concrete 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
    

提交回复
热议问题