title: Nearest "n" rolling join in R data table
body: <p>With <code>data.table</code>, we can join a value in one data set with the nearest value in another by using <code>roll = &quot;nearest&quot;</code>. Some example data:</p>
  <pre><code>dt1 &lt;- data.table(x = c(15,101), id1 = c(&quot;x&quot;, &quot;y&quot;))
  dt2 &lt;- data.table(x = c(10,50,100,200), id2 = c(&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;))
  </code></pre>
  <p>Using <code>roll = &quot;nearest&quot;</code>, I can join each 'x' in 'dt1' with the 'x' in dt2 which is nearest:</p>
  <pre><code>dt2[dt1, roll = &quot;nearest&quot;, on = &quot;x&quot;]
  #     x  id2 id1
  # 1: 15    a   x
  # 2: 101   c   y
  </code></pre>
  <p>E.g. for <code>x = 15</code> in 'dt1', the nearest <code>x</code> value in 'dt2' is <code>x = 10</code>, and we get the corresponding 'id2' which is <code>&quot;a&quot;</code>.</p>
  <p>But what if instead of getting <em>one</em> nearest value, I want to get <em>n</em> nearest values? For example, if I want the <em>2</em> nearest x values, the result would be:</p>
  <pre><code>     x id2 id1  roll
  1:  15   a   x   nr1
  2:  15   b   x   nr2
  3: 101   c   y   nr1
  4: 101   b   y   nr2
  </code></pre>
  <p>(&quot;nr&quot; stands for &quot;nearest&quot;)</p>
  <p>I want a general approach that I can apply to any &quot;n&quot; (e.g. 2 nearest points, 3 nearest points, etc).</p>
  <hr />
  <p><strong>EDIT</strong>
  I wonder if it is possible to also apply this to multi columns join where the join will match on the preceding column before getting the nearest on the last join column. For example:</p>
  <pre><code>dt1 &lt;- data.table(group=c(1,2), x=(c(15,101)), id1=c(&quot;x&quot;,&quot;y&quot;))
  dt2 &lt;- data.table(group=c(1,2,2,3), x=c(10,50,100,200),id2=c(&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;))
  </code></pre>
  <p>If I join <code>on=c(&quot;group&quot;,&quot;x&quot;)</code>, the join will first match on &quot;group&quot; and then get the nearest on &quot;x&quot;, so I would expect the result to be something like:</p>
  <pre><code>     x  group id2 id1  roll
  1:  15      1   a   x   nr1
  2: 101      2   c   y   nr1
  3: 101      2   b   y   nr2
  </code></pre>