Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

For example if

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

I want to return indices of x for each entry of y:

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

I can do this easily by looping over y, but I want to know if there is a way to vectorize this. So can I vectorize:

for (k in 1:length(y)){
    max(which(x < y[k]))
}
like image 404
user39531 Avatar asked Jul 02 '15 18:07

user39531


People also ask

How do you find the largest value in a vector in R?

In R, we can find the minimum or maximum value of a vector or data frame. We use the min() and max() function to find minimum and maximum value respectively. The min() function returns the minimum value of a vector or data frame. The max() function returns the maximum value of a vector or data frame.

How do you find greater than in R?

You can also check whether an R-object is greater than or equal to (>=) (or less than or equal to <= ) another R-object. To achieve this, you can use the less than or equal to sign in combination with an equal sign.

How do I find the greatest value in R?

Max() function in R For this, we first create a vector and then apply the max() function, which returns the max value in the vector.

How do you select a row with maximum value in each group in R language?

Row wise maximum of the dataframe or maximum value of each row in R is calculated using rowMaxs() function. Other method to get the row maximum in R is by using apply() function. row wise maximum of the dataframe is also calculated using dplyr package.


2 Answers

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)
like image 27
C_Z_ Avatar answered Oct 23 '22 18:10

C_Z_


Assuming x is sorted, the findInterval function will work:

findInterval(y,x)
# 2 4
like image 69
Frank Avatar answered Oct 23 '22 18:10

Frank