K-means clustering in R

See Video ⮞ ☝


Introduction

K-means partitions numeric observations into a prespecified number of clusters by minimizing the within-cluster sum of squared Euclidean distances. Each observation is assigned to the cluster whose centroid is nearest under the chosen feature scaling.

The algorithm alternates between assigning observations to clusters and updating centroids. Because the solution can depend on initial centers, use multiple starts and assess whether the resulting partition is stable.

Let's get started

Import data file

Clear objects from the workspace only if needed, after saving anything to retain. Closing graphics devices and clearing the console are optional.

rm(list = ls(all = TRUE))
graphics.off()
shell("cls")

Import the CSV file with the correct path and header setting. Inspect the data types, missing values, and variable definitions before selecting the features for clustering.

data <- read.csv(file = "data_kmeans.csv", 
                 header = TRUE)
head(data)
#            X Murder Assault UrbanPop Rape
# 1    Alabama   13.2     236       58 21.2
# 2     Alaska   10.0     263       48 44.5
# 3    Arizona    8.1     294       80   NA
# 4   Arkansas    8.8     190       50 19.5
# 5 California    9.0     276       91 40.6
# 6   Colorado    7.9     204       78 38.7

Observe data & format variables

The first column identifies US states and should not enter the distance calculation as a numeric feature. Convert identifiers to character or row names, and keep the numeric measurements separate from labels.

str(data)
# 'data.frame': 30 obs. of  5 variables:
#  $ X       : Factor w/ 30 levels "Alabama","Alaska",..: 1 2 3 4 5 6 7 8 9 10 ...
#  $ Murder  : num  13.2 10 8.1 8.8 9 7.9 3.3 5.9 15.4 17.4 ...
#  $ Assault : int  236 263 294 190 276 204 110 238 335 NA ...
#  $ UrbanPop: int  58 48 80 50 91 78 77 72 80 60 ...
#  $ Rape    : num  21.2 44.5 NA 19.5 40.6 38.7 11.1 15.8 31.9 25.8 ...
data$X <- as.character(x = data$X)
str(data)
# 'data.frame': 30 obs. of  5 variables:
#  $ X       : chr  "Alabama" "Alaska" "Arizona" "Arkansas" ...
#  $ Murder  : num  13.2 10 8.1 8.8 9 7.9 3.3 5.9 15.4 17.4 ...
#  $ Assault : int  236 263 294 190 276 204 110 238 335 NA ...
#  $ UrbanPop: int  58 48 80 50 91 78 77 72 80 60 ...
#  $ Rape    : num  21.2 44.5 NA 19.5 40.6 38.7 11.1 15.8 31.9 25.8 ...

State names can be assigned as row names so they remain attached to the observations in plots and output. Verify that row names are unique and in the same order as the measurement rows.

rownames(data) <- data$X
head(data)
#                     X Murder Assault UrbanPop Rape
# Alabama       Alabama   13.2     236       58 21.2
# Alaska         Alaska   10.0     263       48 44.5
# Arizona       Arizona    8.1     294       80   NA
# Arkansas     Arkansas    8.8     190       50 19.5
# California California    9.0     276       91 40.6
# Colorado     Colorado    7.9     204       78 38.7

Remove the identifier from the feature matrix by explicit column selection. Use names rather than a positional exclusion when the file structure may change.

df <- data[,-1]
head(df)
#            Murder Assault UrbanPop Rape
# Alabama      13.2     236       58 21.2
# Alaska       10.0     263       48 44.5
# Arizona       8.1     294       80   NA
# Arkansas      8.8     190       50 19.5
# California    9.0     276       91 40.6
# Colorado      7.9     204       78 38.7

Complete-case deletion with na.omit() can remove rows and change the sample. Check how many observations are dropped and consider an appropriate missing-data strategy before clustering.

na.pass() returns the object unchanged
df <- na.omit(df)

k-means Clustering

Load factoextra for cluster-number diagnostics and visualization. Install the package once if it is not already available.

require(factoextra)

Determine and visualize the optimal number of clusters

K-means requires the number of clusters to be chosen in advance. Evaluate several candidate values and use subject-matter interpretability, diagnostics, and stability rather than treating one plot as a definitive answer.

Several diagnostics can help compare candidate cluster counts, but they measure different properties and may disagree.

fviz_nbclust() can visualize within-cluster sums of squares, average silhouette width, or the gap statistic. These are exploratory criteria; none guarantees a uniquely correct number of clusters.

The gap statistic can be inspected with fviz_gap_stat(). Select the rule used to identify a candidate number of clusters and report it; do not rely only on visual inspection.

Supply a numeric feature matrix to the cluster-count diagnostic. Standardize variables when their units or ranges would otherwise dominate Euclidean distance, or justify using the original scales.

`x` can be the results of the function NbClust().

The clustering function supplied to fviz_nbclust() must accept the feature matrix and candidate cluster count and return cluster assignments. Check the function documentation for the expected interface.

Allowed values include:
kmeans, cluster::pam, cluster::clara, cluster::fanny, hcut, etc. 
This argument is not required when x is an output of the function `NbClust()`. 

Choose the diagnostic method explicitly: within-cluster sum of squares, average silhouette width, or gap statistic. Each assesses a different aspect of partition quality.

The following choices correspond to the common diagnostics available in the function.

Average silhouette width summarizes how well observations fit their assigned cluster relative to neighboring clusters; larger average values are generally preferred.

Within-cluster sum of squares decreases as the number of clusters increases. An elbow can suggest a useful compromise, but its location can be subjective.

The gap statistic compares observed within-cluster dispersion with a reference distribution. Use the selection rule implemented for the chosen method and report the candidate cluster count.

A reference line on the diagnostic plot should mark the selected candidate value and be described in the caption. It is a visual aid, not an additional statistical test.

# Optimal number of clusters
fviz_nbclust(x = df, 
             FUNcluster = kmeans, 
             method = "wss") +
# To draw reference line
          geom_vline(xintercept = 4, 
                     linetype = 2) + 
# Add subtitle "Elbow method"
          labs(subtitle = "Elbow method")

Set a random seed to make the random initialization reproducible. The seed does not eliminate sensitivity to initialization; increase nstart and compare solutions.

The plot showed that the optimal number of clusters are four as shown by the bent (elbow) of the curve.    

Computing k-means clusters on a data matrix

Pass the numeric feature matrix and chosen cluster count to kmeans(). The nstart argument requests multiple random initial configurations. Standardization is particularly important for the USArrests variables, which are measured on different scales, if equal weighting is intended.

Inspect cluster assignments, centers, within-cluster sums of squares, and cluster sizes. Empty or very small clusters and markedly different solutions across starts may indicate an unstable partition.

set.seed(123)
require(stats)
km.res <- kmeans(x = df, 
                 centers = 4, 
                 nstart = 25)
print(km.res)
# K-means clustering with 4 clusters of sizes 4, 2, 10, 9
# 
# Cluster means:
#     Murder Assault UrbanPop     Rape
# 1  8.27500  182.75 71.75000 26.30000
# 2 13.35000  317.50 73.50000 29.85000
# 3  4.42000   92.20 62.10000 14.67000
# 4 11.58889  253.00 68.55556 29.61111
# 
# Clustering vector:
#     Alabama      Alaska    Arkansas  California    Colorado Connecticut 
#           4           4           1           4           1           3 
#    Delaware     Florida      Hawaii       Idaho    Illinois        Iowa 
#           4           2           3           3           4           3 
#      Kansas    Kentucky   Louisiana       Maine    Maryland    Michigan 
#           3           3           4           3           2           4 
#   Minnesota Mississippi    Missouri     Montana    Nebraska      Nevada 
#           3           4           1           3           3           4 
#  New Jersey 
#           1 
# 
# Within cluster sum of squares by cluster:
# [1] 2165.068  713.810 7470.237 4494.920
#  (between_SS / total_SS =  91.7 %)
# 
# Available components:
# 
# [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
# [6] "betweenss"    "size"         "iter"         "ifault"

Use aggregate() to summarize feature means by assigned cluster. These means help describe the groups but should be interpreted on the scale used for clustering; if features were standardized, transform summaries back for practical interpretation.

km.res$cluster
km.res$centers
km.res$size

Directly computing means using aggregate function

Append the cluster assignment to the original data using row order only after verifying that the feature matrix has not reordered or dropped observations. Preserve state labels and document any excluded rows.

aggregate(x = df, 
          by = list(cluster = km.res$cluster), 
          FUN = mean)
#   cluster   Murder Assault UrbanPop     Rape
# 1       1  8.27500  182.75 71.75000 26.30000
# 2       2 13.35000  317.50 73.50000 29.85000
# 3       3  4.42000   92.20 62.10000 14.67000
# 4       4 11.58889  253.00 68.55556 29.61111

Point classifcation of original data

Report the preprocessing, distance metric, number-of-clusters selection rule, random seed, number of starts, and cluster sizes. Clusters are exploratory summaries of these data, not necessarily naturally occurring or externally validated groups.

dd <- cbind(df, 
            cluster = km.res$cluster)
head(dd)
#             Murder Assault UrbanPop Rape cluster
# Alabama       13.2     236       58 21.2       4
# Alaska        10.0     263       48 44.5       4
# Arkansas       8.8     190       50 19.5       1
# California     9.0     276       91 40.6       4
# Colorado       7.9     204       78 38.7       1
# Connecticut    3.3     110       77 11.1       3
Please comment below if you have any questions

Download data file — Click_here

Download Rscript — Download Rscript


Download R program — Click_here

Download R studio — Click_here


Comments