title: Fast way of getting index of match in list
body: <p>Given a list <code>a</code> containing vectors of unequal length and a vector <code>b</code> containing some elements from the vectors in <code>a</code>, I want to get a vector of equal length to <code>b</code> containing the index in <code>a</code> where the element in <code>b</code> matches (this is a bad explanation I know)...</p>
  
  <p>The following code does the job:</p>
  
  <pre><code>a &lt;- list(1:3, 4:5, 6:9)
  b &lt;- c(2, 3, 5, 8)
  
  sapply(b, function(x, list) which(unlist(lapply(list, function(y, z) z %in% y, z=x))), list=a)
  [1] 1 1 2 3
  </code></pre>
  
  <p>Replacing the <code>sapply</code> with a for loop achieves the same of course</p>
  
  <p>The problem is that this code will be used with list and vectors with a length above 1000. On a real life set the function takes around 15 seconds (both the for loop and the <code>sapply</code>).</p>
  
  <p>Does anyone have an idea how to speed this up, safe for a parallel approach? I have failed to see a vectorized approach (and I cannot program in C, though that would probably be the fastest).</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>Will just emphasize Aaron's elegant solution using match() which gave a speed increase in the order of 1667 times (from 15 to 0.009)</p>
  
  <p>I expanded a bit on it to allow multiple matches (the return is then a list)</p>
  
  <pre><code>a &lt;- list(1:3, 3:5, 3:7)
  b &lt;- c(3, 5)
  g &lt;- rep(seq_along(a), sapply(a, length))
  sapply(b, function(x) g[which(unlist(a) %in% x)])
  [[1]]
  [1] 1 2 3
  
  [[2]]
  [1] 2 3
  </code></pre>
  
  <p>The runtime for this was 0.169 which is arguably quite slower, but on the other hand more flexible</p>