title: R: By group, check if for each unique value of one var, there is at least one observation where the value of the var equals the value of another var
body: <p>I think I am on the right direction with this code, but I am not quite there yet.</p>
  
  <p>I tried finding something useful on Google and SE, but I did not seem to be able to formulate the question in a way that gets me the answer I am looking for.</p>
  
  <p>I <em>could</em> write a <em>for-loop</em> for this, comparing for each <em>id</em> and for each unique value of <em>a</em> per row, but I strive to achieve a higher level of R-understanding and thus want to avoid loops.</p>
  
  <pre><code>id &lt;- c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5)
  a &lt;- c(1,1,1,2,2,2,3,3,4,4,4,5,5,5,6)
  b &lt;- c(1,2,3,3,3,4,3,4,5,4,4,5,6,7,8)
  
  require(data.table)
  dt &lt;- data.table(id, a, b)
  
  dt
  dt[,unique(a) %in% b, by=id]
  tmp &lt;- dt[,unique(a) %in% b, by=id]
  tmp$id[tmp$V1 == FALSE]
  </code></pre>
  
  <p>In my example, <em>IDs</em> 2, 3 and 5 should be the result, the decision rule being: "By <em>id</em>, check if for each unique value of <em>a</em> if there is at least one observation where the value of <em>b</em> equals value of <em>a</em>."</p>
  
  <p>However, my code only outputs <em>IDs</em> 2 and 5, but not 3. This is because for <em>ID</em> 3, the <em>4</em> is matched with the <em>4</em> of the previous observation.</p>
  
  <p>The result should either output the IDs for which the condition is not met, or add a dummy variable to the original table that indicated whether the condition is met for the ID.</p>