title: Optimization : conditional test on several matrices & extraction in R
body: <p>I have a matrix</p>
  
  <pre><code>mat_a &lt;- matrix(data = c( c(rep(1,3), rep(2,3), rep(3,3))
    , rep(seq(1,300,100), 3)
    , runif(15, 0, 1))
  , ncol=3)
  
        [,1] [,2]      [,3]
   [1,]    1    1 0.8393401
   [2,]    1  101 0.5486805
   [3,]    1  201 0.4449259
   [4,]    2    1 0.3949137
   [5,]    2  101 0.4002575
   [6,]    2  201 0.3288861
   [7,]    3    1 0.7865035
   [8,]    3  101 0.2581155
   [9,]    3  201 0.8987769
  </code></pre>
  
  <p>that I compare to another matrix with higher dimensions</p>
  
  <pre><code>mat_b &lt;- matrix(data = c(
    c(rep(1,3), rep(2,3), rep(3,3), rep(4,3))
    , rep(seq(1,300,100), 4)
    , rep(3:5, 4))
  , ncol = 3)
        [,1] [,2] [,3]
   [1,]    1    1    3
   [2,]    1  101    4
   [3,]    1  201    5
   [4,]    2    1    3
   [5,]    2  101    4
   [6,]    2  201    5
   [7,]    3    1    3
   [8,]    3  101    4
   [9,]    3  201    5
  [10,]    4    1    3
  [11,]    4  101    4
  [12,]    4  201    5
  </code></pre>
  
  <p>I need to extract the lines of <code>mat_a</code> where columns #2 of both matrices match. For those matches, both columns 1 also have to match. Also, column 3 of <code>mat_b</code> must be higher or equal to 4.
  I cannot find any solution based on vectorization. I only came out with a loop-based solution.</p>
  
  <pre><code>output &lt;- NULL
  for (i in 1:nrow(mat_a)) {
    if (mat_a[i,2] %in% mat_b[,2][mat_b[,3] &gt;= 4]) { 
      rows &lt;- which( mat_b[,2] %in% mat_a[i,2]) 
      row &lt;- which(mat_b[,1][rows] == mat_a[i,1])
      if (mat_b[,3][rows[row]] &gt;= 4) {
          output &lt;- rbind(output, mat_a[i,])
      }
    } 
  }
  </code></pre>
  
  <p>This works but is extremely slow. It took less than one hour to run. <code>mat_a</code> has 9 col with 40,000 rows (could go higher), <code>mat_b</code> has 5 col and around 1.2 millions rows.
  Any idea?</p>