title: Outlier detection with k-means algorithm
body: <p>I am hoping you can help me with my problem. I am trying to detect outliers with use of the kmeans algorithm. First I perform the algorithm and choose those objects as possible outliers which have a big distance to their cluster center. Instead of using the absolute distance I want to use the relative distance, i.e. the ration of absolute distance of the object to the cluster center and the average distance of all objects of the cluster to their cluster center. The code for outlier detection based on absolute distance is the following:</p>
  
  <pre><code># remove species from the data to cluster
  iris2 &lt;- iris[,1:4]
  kmeans.result &lt;- kmeans(iris2, centers=3)
  # cluster centers
  kmeans.result$centers
  # calculate distances between objects and cluster centers
  centers &lt;- kmeans.result$centers[kmeans.result$cluster, ]
  distances &lt;- sqrt(rowSums((iris2 - centers)^2))
  # pick top 5 largest distances
  outliers &lt;- order(distances, decreasing=T)[1:5]
  # who are outliers
  print(outliers)
  </code></pre>
  
  <p>But how can I use the relative instead of the absolute distance to find outliers?</p>