Search code examples
rvectorization

R - vectorizing first value of an array that is greater of some threshold


I need to find the first value of an array that is greater of some scalar threshold y. I am using

array[min(which(array > y))]

This gives me a 1x1 element that is the first value of array greater than y. Now, I would like to vectorize this operation somehow. In particular, if y is a m x 1 vector, I would like to compare array to each of the elements of y and return me a m x 1 vector where element in position i is the first value of array greater than y[i]. How can I do that without for loops?


Solution

  • f <- function(array, y) array[min(which(array > y))]
    
    f_vectorized <- Vectorize(f, "y")
    
    f(array = 1:10, y = c(4, 8, 3))
    #> [1] 5 9 4