title: ifelse function group in group in R
body: <p>I have data set</p>
  
  <pre><code>ID &lt;- c(1,1,2,2,2,2,3,3,3,3,3,4,4,4)
  Eval &lt;- c("A","A","B","B","A","A","A","A","B","B","A","A","A","B")
  med &lt;- c("c","d","k","k","h","h","c","d","h","h","h","c","h","k")
  df &lt;- data.frame(ID,Eval,med)
  &gt; df
      ID Eval med
   1   1    A   c
   2   1    A   d
   3   2    B   k
   4   2    B   k
   5   2    A   h
   6   2    A   h
   7   3    A   c
   8   3    A   d
   9   3    B   h
   10  3    B   h
   11  3    A   h
   12  4    A   c
   13  4    A   h
   14  4    B   k
  </code></pre>
  
  <p>I try to create variable <code>x</code> and <code>y</code>, group by ID and Eval. For each ID, <code>if Eval = A, and med = "h" or "k"</code>, I set <code>x = 1</code>, other wise <code>x = 0</code>, <code>if Eval = B and med = "h" or "k"</code>, I set <code>y = 1</code>, other wise <code>y = 0</code>. I use the way I don't like it, I got answer but it seem like not that great</p>
  
  <pre><code>df &lt;- data.table(df)
  setDT(df)[, count := uniqueN(med) , by = .(ID,Eval)]
  setDT(df)[Eval == "A", x:= ifelse(count == 1 &amp; med %in% c("k","h"),1,0), by=ID]
  setDT(df)[Eval == "B", y:= ifelse(count == 1 &amp; med %in% c("k","h"),1,0), by=ID]
  
  
       ID Eval med count  x  y
   1:  1    A   c     2  0 NA
   2:  1    A   d     2  0 NA
   3:  2    B   k     1 NA  1
   4:  2    B   k     1 NA  1
   5:  2    A   h     1  1 NA
   6:  2    A   h     1  1 NA
   7:  3    A   c     3  0 NA
   8:  3    A   d     3  0 NA
   9:  3    B   h     1 NA  1
  10:  3    B   h     1 NA  1
  11:  3    A   h     3  0 NA
  12:  4    A   c     2  0 NA
  13:  4    A   h     2  0 NA
  14:  4    B   k     1 NA  1
  </code></pre>
  
  <p>Then I need to collapse the row to get unique ID, I don't know how to collapse rows, any idea? </p>
  
  <p>The output </p>
  
  <pre><code> ID x y
   1  0 0
   2  1 1
   3  0 1
   4  0 1
  </code></pre>