This question already has an answer here:
- how to get all the numbers greater than x with positions? 1 answer
In R: I have a vector and want to find the position of the first value that is greater than 100.
This question already has an answer here:
In R: I have a vector and want to find the position of the first value that is greater than 100.
# Randomly generate a suitable vector
set.seed(0)
v <- sample(50:150, size = 50, replace = TRUE)
min(which(v > 100))
Most answers based on which
and max
are slow (especially for long vectors) as they iterate through the entire vector:
x>100
evaluates every value in the vector to see if it matches the conditionwhich
and max
/min
search all the indexes returned at step 1. and find the maximum/minimumPosition
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.
Position(function(x) x > 100,x)
Check out which.max
:
x <- seq(1, 150, 3)
which.max(x > 100)
# [1] 35
x[35]
# [1] 103
Just to mention, Hadley Wickham has implemented a function, detect_index
, to do exactly this task in his purrr
package for functional programming.
I recently used detect_index
myself and would recommend it to anyone else with the same problem.
Documentation for detect_index
can be found here: https://rdrr.io/cran/purrr/man/detect.html
There are many solutions, another is:
x <- 90:110
which(x > 100)[1]
Assuming values is your vector.
firstGreatearThan <- NULL
for(i in seq(along=values)) {
if(values[i] > 100) {
firstGreatearThan <- i
break
}
}