title: Vectorize R command (part 2)
body: <p>Yesterday <a href="https://stackoverflow.com/questions/37331375/vectorize-min-for-matrix/37331414#37331414">I asked</a> a very simple vectorization question and got some great answers. Today the question is a bit more complex and I'm wondering if <code>R</code> has a function to speed up the runtime of this loop through vectorization.</p>
  
  <p>The loop is </p>
  
  <pre><code>for(j in 1:N) {
      A[j,1] = B[max(which(C[j]&gt;=D))];
  }
  </code></pre>
  
  <p>I tried </p>
  
  <pre><code>A[,1] = B[max(which(C&gt;=D))];
  </code></pre>
  
  <p>and this dropped the runtime considerably ... but the answer was wrong. Is there a "correct" way to do this in R?</p>
  
  <p><strong>EDIT1:</strong></p>
  
  <p>Thanks for the questions regarding data. I will give sizes of the arrays here:</p>
  
  <p>We are looping over <code>1:N</code></p>
  
  <pre><code> A is N x 1
   B is length M
   C is length N
   D is length M
  </code></pre>
  
  <p>If it matters in terms of speed, in this example, <code>N = 844</code>, <code>M = 2500</code>.</p>
  
  <p><strong>Edit2:</strong></p>
  
  <p>And here are some values for a smaller simulated dataset:</p>
  
  <pre><code>B &lt;- c(1.0000000, 1.0000000, 1.0000000, 0.9565217, 0.9565217, 0.9565217, 0.9565217,
  0.9565217, 0.9565217, 0.9565217, 0.8967391, 0.8369565, 0.7771739, 0.7173913,
  0.7173913, 0.7173913, 0.7173913, 0.7173913, 0.6277174, 0.6277174, 0.5230978,
  0.5230978, 0.3923234, 0.3923234, 0.3923234)
  C &lt;- c(0.10607, 0.14705, 0.43607, 0.56587, 0.76203, 0.95657, 1.03524, 1.22956, 1.39074, 2.36452)
  D &lt;- c(0.10607, 0.13980, 0.14571, 0.14705, 0.29412, 0.33693, 0.43607, 0.53968, 0.56587,
  0.58848, 0.64189, 0.65475, 0.75518, 0.76203, 0.95657, 1.03524, 1.05454, 1.18164,
  1.22956, 1.23760, 1.39074, 1.87604, 2.36452, 2.89497, 4.42393)
  </code></pre>
  
  <p>The result should be:</p>
  
  <pre><code> &gt; A
             [,1]
   [1,] 1.0000000
   [2,] 0.9565217
   [3,] 0.9565217
   [4,] 0.9565217
   [5,] 0.7173913
   [6,] 0.7173913
   [7,] 0.7173913
   [8,] 0.6277174
   [9,] 0.5230978
  [10,] 0.3923234
  </code></pre>