title: Computing pairwise Hamming distance between all rows of two integer matrices/data frames
body: <p>I have two data frames, <code>df1</code> with reference data and <code>df2</code> with new data. For each row in <code>df2</code>, I need to find the best (and the second best) matching row to <code>df1</code> in terms of hamming distance.</p>
  
  <p>I used <code>e1071</code> package to compute hamming distance. Hamming distance between two vectors <code>x</code> and <code>y</code> can be computed as for example:</p>
  
  <pre><code>x &lt;- c(356739, 324074, 904133, 1025460, 433677, 110525, 576942, 526518, 299386,
         92497, 977385, 27563, 429551, 307757, 267970, 181157, 3796, 679012, 711274,
         24197, 610187, 402471, 157122, 866381, 582868, 878)
  
  y &lt;- c(356739, 324042, 904133, 959893, 433677, 110269, 576942, 2230, 267130,
         92496, 960747, 28587, 429551, 438825, 267970, 181157, 36564, 677220,
         711274, 24485, 610187, 404519, 157122, 866413, 718036, 876)
  
  xm &lt;- sapply(x, intToBits)
  ym &lt;- sapply(y, intToBits)
  
  distance &lt;- sum(sapply(1:ncol(xm), function(i) hamming.distance(xm[,i], ym[,i])))
  </code></pre>
  
  <p>and the resulting distance is 25. Yet I need to do this for all rows of <code>df1</code> and <code>df2</code>. A trivial method takes a double loop nest and looks terribly slow.</p>
  
  <p>Any ideas how to do this more efficiently? In the end I need to append to <code>df2</code>:</p>
  
  <ul>
  <li>a column with the row id from <code>df1</code> that gives the lowest distance;</li>
  <li>a column with the lowest distance;</li>
  <li>a column with the row id from <code>df1</code> that gives the 2nd lowest distance;</li>
  <li>a column with the second lowest distance.</li>
  </ul>
  
  <p>Thanks.</p>