title: Distance calculation on large vectors [performance]
body: <p>Hi guys I have a following problem I have cluster centers in some dimmentions (4-6 clusters) and a very large dataset that I need to assign each row to the closest cluster. So it's not really a question of distance but of performance my code is as follows:</p>
  
  <pre><code>distances &lt;- matrix(NA, nrow = nrow(ClusterCenters), ncol = nrow(data))
  calcData &lt;- data[, colnames(ClusterCenters), drop=FALSE]
  for(i in 1:nrow(ClusterCenters)) {
      distances[i,] &lt;- (rowSums((matrix(unlist(apply(calcData, 1, function(x) {x - ClusterCenters[i,]})), ncol = ncol(calcData), byrow = TRUE))^2))^0.5
  }
  ClusterMemberships &lt;- vector(mode="numeric", length=nrow(calcData))
  for(i in 1: nrow(calcData)) {
    ClusterMemberships[i] &lt;- which.min(distances[,i])
  }
  return(ClusterMemberships)
  </code></pre>
  
  <p>Is there a way to speed it up? I work on windows server.</p>