# k-means clustering unclear result

I am new in datamining. I decided to play with k-means clustering in r with simple аrtificial data.

set.seed(101)
x1 <- runif(100,36.6,37.5)
x2 <- runif(100,37.6,38.4)
x3 <- runif(100,38.5,40)
x<-c(50,150,250)
y<-c(37,38,39.25)

centers<-c(37.05,38,39.25)
all <- c(x1,x2,x3)
c1<-kmeans(all,centers=centers,iter.max = 1000,nstart=1,algorithm="Lloyd")
plot(all,col = c1\$cluster)
points(x,y,col="red",pch=19)


I generated three random data sets x1,x2,x3. Then i taked center of each cluster like mean of each set and used k-means algorith of r. In result i get what you see in picture.

What i am making wrong?

Why second cluster contains the part of third set? How to improve result?

The main question is how to improve clustreing result?

A 1 dimensional data set is "linearly separable" at any set of points between the data points. Kmeans isn't a nearest-neighbour type of clustering algorithm, it just divides the space so that each point belongs to its nearest cluster centre, so your data could have huge gaps between the source clusters, but the algorithm would be "wrong" if the clusters had different ranges.

For example, if you generate points from two clusters on the intervals (0,1) and (2,20), even though there's a gap between 1 and 2, the clustering algorithm will still assign a lot of the points from the higher source cluster to the lower cluster because they are nearer that cluster centre. Its distance to cluster centre for each points that counts, not distance to neighbours. Use another clustering algorithm (like nearest-neighbours) if you are expecting gaps between clusters.