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

Time:09-12

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?

CodePudding user response:

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

CodePudding user response:

One problem exists if no value in the array is greater than y. We can use NA propagation for such cases.

set.seed(5)
a <- array(sample(100, 12), c(2,2,3)) # no value greater than 100

y <- c(80, 100, 2, 90, NA)

m <- !outer(y, c(a), ">")
max.col(m, "first") * NA^!rowSums(m)

#> [1]  6 NA  1  7 NA
  • Related