CesiumLifeJacket
CesiumLifeJacket

Reputation: 93

Find index of value in a sorted vector in R

I have an ordered vector of unique integers in R and I want to find the index of the element closest to but less than or equal to some value. For example, for the vector 4 8 15 16 23 42 and the search value 17, I would like the function to return 4, the index of 16. In Python, I would use bisect module. Is there anything similar in R?

Upvotes: 6

Views: 3213

Answers (1)

jan-glx
jan-glx

Reputation: 9486

Base R provides findInterval, which implements a binary search:

findInterval(17, c(4, 8, 15, 16, 23, 42))

@Khashaa already mentioned this in a comment.

Upvotes: 8

Related Questions