Find nearest smaller number

前端 未结 7 1271
粉色の甜心
粉色の甜心 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:57

    You could 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)
    

    That way if x is not in f, it will return the nearest previous index. If x is in f, it will return x index.

提交回复
热议问题