title: Speeding up a for loop (or moving away from it), with some decision rules
body: <p>I have a for loop, which attempts to check that, for every element in a vector <code>vals</code> it is contained exactly two times in 4 different vectors (<code>dp</code>, <code>up</code>, <code>de</code>, <code>ue</code>), but:</p>
  
  <ol>
  <li>should only be found exactly once in <code>dp</code> or <code>de</code> and;</li>
  <li>should only be found exactly once in <code>up</code> or <code>ue</code></li>
  </ol>
  
  <p>The vectors that I am trying to check are in the millions of elements, and it's taking hours, I'm thinking the below code could be sped up.</p>
  
  <p>MRE:</p>
  
  <pre><code>vals &lt;- c('a', 'b', 'c', 'd', 'e', 'f') # 6 elements to be verified
  
  # only 1 of these two
  dp &lt;- c('a', 'c', 'd','f', 'f')
  de &lt;- c('b','a', 'd')
  # only one of these two
  up &lt;- c('b', 'd', 'e')
  ue &lt;- c('c')    
  
  i &lt;- list()
  for (val in vals) {
    dipa &lt;- sum(grepl(val, dp)) # attemps to find val in dp and sums
    ulpa &lt;- sum(grepl(val, up)) # attemps to find val in up and sums
    diex &lt;- sum(grepl(val, de)) # attemps to find val in de and sums
    ulex &lt;- sum(grepl(val, ue)) # attemps to find val in ue and sums
    f &lt;- sum(sum(dipa) + sum(ulpa) + sum(diex) + sum(ulex)) == 2 # sum two # overall, it has to be found 2 times exactly
    pars &lt;- dipa + diex == 1 # once in dipa or diex
    excs &lt;- ulpa + ulex == 1 # once in ulpa or ulex
    if(isTRUE(f) &amp; isTRUE(pars) &amp; isTRUE(excs)) {
      i[val] &lt;- 1 #if all of these 3 conditions are true, then add
    } else {
      next
    }
  }
  </code></pre>
  
  <p>In the example above, <code>i</code> should hold only:</p>
  
  <ol>
  <li><code>b</code> (because it is found once in <code>up</code> and once in <code>de</code></li>
  <li><code>c</code> (because it is found once in <code>dp</code> and once in <code>ue</code></li>
  </ol>
  
  <p>Every element of vals can appear as many times in any of the 4 other vectors, but ideally would only appear twice with the restrictions above.</p>