Find the largest element in a vector less than the values ​​in another vector in R

I have a sorted vector x and another vector y (not necessarily the same length). For each record y, I want to find the index of the largest record x, which is less than or equal to record y.

For example, if

x <- c(2,4,8,9,12) 
y <- c(5,10)

I want to return indexes xfor each record y:

  • 2 (because 4 is the largest record x is less than 5) and
  • 4.

I can do this easily by going along y, but I want to know if there is a way to vectorize it. So is it possible to vectorize:

for (k in 1:length(y)){
    max(which(x < y[k]))
}
+4
source share
3 answers

Assuming it is xsorted, the function findIntervalwill work:

findInterval(y,x)
# 2 4
+4
source

Using Vectorize:

x <- c(2,4,8,9,12) 
y <- c(5,10)

largest_less_than<-function(x,y){
  which(x == max(x[x < y]))
}

largest_less_than <- Vectorize(largest_less_than, vectorize.args = 'y')

largest_less_than(x = x, y = y)
+2
source

, . x, y , . . , . .

+1
source

All Articles