title: Get first value that matches condition (loop too slow)
body: <p>I've got a lot of matrices similar to this but with thousands of rows :</p>
  
  <pre><code>r &lt;- 10
  c &lt;- 2
  set.seed(333)
  
  m1 &lt;- matrix(runif(r*c)+1, r, c)
  
  &gt; m1
            [,1]     [,2]
   [1,] 1.467001 1.393902
   [2,] 1.084598 1.474218
   [3,] 1.973485 1.891222
   [4,] 1.571306 1.665011
   [5,] 1.020119 1.736832
   [6,] 1.723557 1.911469
   [7,] 1.609394 1.637850
   [8,] 1.306719 1.864651
   [9,] 1.063510 1.287575
  [10,] 1.305353 1.129959
  </code></pre>
  
  <p>I've got a loop that tells me, for each value of the first column, what is the index of the first value in the second column that is 10% higher like so :</p>
  
  <pre><code>result &lt;- 1:nrow(m1)
  
  for (i in 1:nrow(m1)){
      result[i] &lt;- which(m1[,2]&gt;(1.1*m1[,1][i]))[1]
  }
  &gt; result
   [1]  3  1 NA  3  1  6  3  2  1  2
  </code></pre>
  
  <p>I've got so much matrices that it's taking hours, and after profiling my code, the biggest time consuming task by far is this loop. What is, according to you, the fastest way to do it ?</p>
  
  <p>For example, with r = 30000 :</p>
  
  <pre><code>start_time &lt;- Sys.time()
  
  for (i in 1:nrow(m1)){
      result[i] &lt;- which(m1[,2]&gt;(1.1*m1[,1][i]))[1]
  }
  
  end_time &lt;- Sys.time()
  a &lt;- end_time - start_time
  
  &gt; a
  Time difference of 11.25815 secs
  </code></pre>
  
  <p>Thanks for you help !</p>