Find position of first value greater than X in a vector

前端 未结 6 1312
粉色の甜心
粉色の甜心 2020-12-09 08:53

In R: I have a vector and want to find the position of the first value that is greater than 100.

相关标签:
6条回答
  • 2020-12-09 09:31

    Assuming values is your vector.

     firstGreatearThan <- NULL
      for(i in seq(along=values)) { 
        if(values[i] > 100) {
           firstGreatearThan <- i
           break
        }
     }
    
    0 讨论(0)
  • 2020-12-09 09:32

    Check out which.max:

    x <- seq(1, 150, 3)
    which.max(x > 100)
    # [1] 35
    x[35]
    # [1] 103
    
    0 讨论(0)
  • 2020-12-09 09:34

    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

    0 讨论(0)
  • 2020-12-09 09:36

    There are many solutions, another is:

    x <- 90:110
    which(x > 100)[1]
    
    0 讨论(0)
  • 2020-12-09 09:37

    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)
    
    0 讨论(0)
  • 2020-12-09 09:38
    # Randomly generate a suitable vector
    set.seed(0)
    v <- sample(50:150, size = 50, replace = TRUE)
    
    min(which(v > 100))
    
    0 讨论(0)
提交回复
热议问题