Gaurav Bansal Gaurav Bansal - 25 days ago 12
R Question

R kmeans final distance to to centroid

I have run a

kmeans
algorithm on the
iris
dataset in
R
using the command
kmeans_iris <- kmeans(iris[,1:4], centers=3)
. I now want to know the distance from a given observation in the
iris
dataset to its corresponding cluster's centroid. I could write code to manually calculate the Euclidean distance from an observation to the
centers
corresponding to its cluster, but is there not an easy, built-in way to do this?

Answer

As far as I can tell, there isn't a method for extracting the per case distance. If I understand what you want correctly, you could code your own like:

sqrt(rowSums(iris[,1:4] - fitted(kmeans_iris)) ^ 2)
#[1] 0.058 0.642 0.742 0.742 0.058 1.258 0.442 0.042 1.242 0.542 ...

...for a Euclidean distance.

Comments