title: Calculating all distances between one point and a group of points efficiently in R
body: <p>First of all, I am new to R (I started yesterday).</p>
  
  <p>I have two groups of points, <code>data</code> and <code>centers</code>, the first one of size <code>n</code> and the second of size <code>K</code> (for instance, <code>n = 3823</code> and <code>K = 10</code>), and for each <code>i</code> in the first set, I need to find <code>j</code> in the second with the minimum distance.</p>
  
  <p>My idea is simple: for each <code>i</code>, let <code>dist[j]</code> be the distance between <code>i</code> and <code>j</code>, I only need to use <code>which.min(dist)</code> to find what I am looking for.</p>
  
  <p>Each point is an array of <code>64</code> doubles, so </p>
  
  <pre><code>&gt; dim(data)
  [1] 3823   64
  &gt; dim(centers)
  [1] 10 64
  </code></pre>
  
  <p>I have tried with</p>
  
  <pre><code>for (i in 1:n) {
    for (j in 1:K) {
      d[j] &lt;- sqrt(sum((centers[j,] - data[i,])^2))
    }
    S[i] &lt;- which.min(d)
  }
  </code></pre>
  
  <p>which is extremely slow (with <code>n = 200</code>, it takes more than 40s!!). The fastest solution that I wrote is</p>
  
  <pre><code>distance &lt;- function(point, group) {
    return(dist(t(array(c(point, t(group)), dim=c(ncol(group), 1+nrow(group)))))[1:nrow(group)])
  }
  
  for (i in 1:n) {
    d &lt;- distance(data[i,], centers)
    which.min(d)
  }
  </code></pre>
  
  <p>Even if it does a lot of computation that I don't use (because <code>dist(m)</code> computes the distance between all rows of <code>m</code>), it is way more faster than the other one (can anyone explain why?), but it is not fast enough for what I need, because it will not be used only once. And also, the <code>distance</code> code is very ugly. I tried to replace it with</p>
  
  <pre><code>distance &lt;- function(point, group) {
    return (dist(rbind(point,group))[1:nrow(group)])
  }
  </code></pre>
  
  <p>but this seems to be twice slower. I also tried to use <code>dist</code> for each pair, but it is also slower.</p>
  
  <p>I don't know what to do now. It seems like I am doing something very wrong. Any idea on how to do this more efficiently?</p>
  
  <p>ps: I need this to implement k-means by hand (and I need to do it, it is part of an assignment). I believe I will only need Euclidian distance, but I am not yet sure, so I will prefer to have some code where the distance computation can be replaced easily. <code>stats::kmeans</code> do all computation in less than one second.</p>