Find position of first value greater than X in a v

2019-03-18 02:35发布

问题:

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.

回答1:

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

min(which(v > 100))


回答2:

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.

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



回答3:

Check out which.max:

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


回答4:

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



回答5:

There are many solutions, another is:

x <- 90:110
which(x > 100)[1]


回答6:

Assuming values is your vector.

 firstGreatearThan <- NULL
  for(i in seq(along=values)) { 
    if(values[i] > 100) {
       firstGreatearThan <- i
       break
    }
 }