Most efficient way to get index in a sorted vector in R?

Viewed 66

I have a sorted vector x, and a vector containing limits L (in increasing order with no specific assumptions), I want to store the max index for all limits in x. I have a solution but it seems inefficient.

What is the fastest way to perform this?

x = sort(runif(n = 1e6))
L = sort(runif(n = 100))
index = sapply(L, function(l) which.max(x>l))
1 Answers

You can use findInterval :

x = sort(runif(n = 1e6))
L = sort(runif(n = 100))
findInterval(L, x) + 1
Related