Gaurav Bansal Gaurav Bansal - 2 months ago 28
R Question

R kmeans final distance to to centroid

I have run a

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


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.