Find position of first value greater than X in a vector

Check out which.max:

x <- seq(1, 150, 3)
which.max(x > 100)
# [1] 35
x[35]
# [1] 103

Most answers based on which and max are slow (especially for long vectors) as they iterate through the entire vector:

  1. x>100 evaluates every value in the vector to see if it matches the condition
  2. which and max/min search all the indexes returned at step 1. and find the maximum/minimum

Position will only evaluate the condition until it encounters the first TRUE value and immediately return the corresponding index, without continuing through the rest of the vector.

# Randomly generate a suitable vector
v <- sample(50:150, size = 50, replace = TRUE)

Position(function(x) x > 100, v)

# Randomly generate a suitable vector
set.seed(0)
v <- sample(50:150, size = 50, replace = TRUE)

min(which(v > 100))