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
:
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]))
}
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.
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.
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.
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.
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)
Assuming x
is sorted, the findInterval
function will work:
findInterval(y,x)
# 2 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With