Sina Mozayyan
Sina Mozayyan

Reputation: 25

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

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

Upvotes: 2

Views: 122

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389335

You can use findInterval :

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

Upvotes: 1

Related Questions