title: Most representative instance of a cluster
body: <p>After performing a cluster analysis to my dataset (a dataframe named <em>data.matrix</em>), I added a new column, named <em>cluster</em>, at the end (col 27) containing the cluster name that each instance belongs to.</p>
  
  <p>What I want now, is a representative instance from each cluster. I tried to find the instance having the smallest euclidean distance from the cluster's centroid (and repeat the procedure for each one of my clusters)</p>
  
  <p>This is what I did. Can you think of other -perhaps more elegant- ways? (assume numeric columns with no nulls). </p>
  
  <pre><code>clusters &lt;- levels(data.matrix$cluster)
  cluster_col = c(27)
  
  for (j in 1:length(clusters)) {
      # get the subset for cluster j
      data = data.matrix[data.matrix$cluster == clusters[j],]
  
      # remove the cluster column
      data &lt;- data[,-cluster_col]
  
      # calculate the centroid
      cent &lt;- mean(data)
  
      # copy data to data.matrix_cl, attaching a distance column at the end
      data.matrix_cl &lt;- cbind(data, dist = apply(data, 1, function(x) {sqrt(sum((x - cent)^2))}))
  
      # get instances with min distance
      candidates &lt;- data.matrix_cl[data.matrix_cl$dist == min(data.matrix_cl$dist),]
  
      # print their rownames
      print(paste("Candidates for cluster ",j))
      print(rownames(candidates))
  }
  </code></pre>