title: Finding all matches in a vector in a data.table
body: <p><em>This question is a follow up to <a href="https://stackoverflow.com/questions/14393194/what-is-the-most-efficient-way-to-create-a-column-of-vectors-in-data-table-whe">this previous question</a>.</em></p>
  
  <p>I have a vector of id's, <code>sampleIDs</code>. 
  I also have a data.table, <code>rec_data_table</code>, keyed by bid and containing a column, 
  <code>A_IDs.list</code> where each elements is a collection (a vector) of aIDs. </p>
  
  <p>I would like to create a second data.table containing <code>sampleIDs</code> and where <br>
   For each <code>aID</code>, there is a corresponding vector of all the bIDs for which <br>
  that aID appears in the <code>A_IDs.list</code> column. </p>
  
  <p>Example: </p>
  
  <pre><code>&gt; rec_data_table
     bid counts names_list A_IDs.list
  1: 301     21        C,E       3,NA
  2: 302     21          E         NA
  3: 303      5      H,E,G     8,NA,7
  4: 304     10        H,D        8,4
  5: 305      3          E         NA
  6: 306      5          G          7
  7: 307      6        B,C        2,3
  
  &gt; sampleIDs
  [1] 3 4 8
  
  AB.dt &lt;- data.table(aID=sampleIDs, key="aID")
  
  # unkown step
  AB.dt[ , bIDs := ????  ]
  
  # desired result:
  &gt; AB.dt
      aid     bIDs
  1:    3  301,307
  2:    4      304
  3:    8  303,304
  </code></pre>
  
  <p><HR><BR></p>
  
  <p>I tried several different lines inside the <code>AB.dt[]</code> call. 
    The closest I could get was </p>
  
  <pre><code>rec_data_table[sapply(A_IDs.list, function(lst) aID %in% lst), bID]
  </code></pre>
  
  <p>which will give me the desired result for a given <code>aID</code>, and I can lapply <br>
    over <code>sampleIDs</code> to create a list of vectors and build the desired result. </p>
  
  <p>However, I suspect there must be a more "data.table appropriate" method to accomplish this. Any suggestions are appreciated. </p>
  
  <p><HR><BR></p>
  
  <pre><code>#--------------------------------------------------#
  #           SAMPLE DATA                            #
  
  library(data.table)
  set.seed(101)
  
    rows &lt;- size &lt;- 7
    varyingLengths &lt;- c(sample(1:3, rows, TRUE))
    A &lt;-  lapply(varyingLengths, function(n) sample(LETTERS[1:8], n))
    counts &lt;- round(abs(rnorm(size)*12))   
  rec_data_table &lt;- data.table(bID=300+(1:size), counts=counts, names_list=A, key="bID")
  
  A_ids.DT &lt;- data.table(name=LETTERS[c(1:4,6:8,10:11)], id=c(1:4,6:8,10:11), key="name")
  rec_data_table[, A_IDs.list := sapply(names_list, function(n) c(A_ids.DT[n, id]$id))]
  sampleIDs &lt;- c(3, 4, 8)
  </code></pre>