R PROGRAMMING & MACHINE LEARNING

K-Means & Hierarchical Clustering in R: Code & Tutorial

Master unsupervised cluster analysis in R. Learn how to import data, handle missing values, scale variables with caret, build elbow charts, fit K-Means (\(k=5\)), perform hierarchical clustering (\(k=4\)), and profile clusters with boxplots.

Need Help With R Clustering Assignments or Code Scripts?

Stuck on an RStudio homework set involving K-Means, hierarchical dendrograms, principal components, or statistical report writing? Our R programming experts deliver clean code and custom APA written reports with a guaranteed A/B grade.

Get R Assignment Help Now

Cluster analysis is one of the most powerful unsupervised machine learning techniques in business analytics and data science. Its goal is to partition observations (such as Yelp user profiles or customer datasets) into homogeneous groups based on similarity across multiple numerical metrics.

Complete R Code: Yelp Dataset Clustering

Below is the complete, annotated R script covering data loading, standardization, K-Means modeling (\(k=5\)), hierarchical clustering with complete linkage (\(k=4\)), and cluster profiling:

# Load the Yelp data from Excel file
library(readxl)
df = read_excel("~/Downloads/Yelp.xlsx")

# Check structure of data
str(df)

# Remove records with missing values
df = na.omit(df)

# Question 1: count number of observations
nrow(df)


### STANDARDIZE THE DATA
# k-means is distance-based, so we should standardize the data
library(caret)

# Remove ID column before standardization (non-numeric)
df_numeric = df[, -1]  # Remove ID column

# Standardize numeric variables
standardizer = preProcess(df_numeric, method = c("scale", "center"))
df_CS = predict(standardizer, df_numeric)


### CHOOSE THE NUMBER OF CLUSTERS
# Load BabsonAnalytics
source("~/Downloads/BabsonAnalytics.R")

# Create elbow chart
elbowChart(df_CS)

# Run model with k=5 clusters
model_k5 = kmeans(df_CS, 5)

# View cluster centers
model_k5$centers

# How many are in each cluster?
model_k5$size

# Add cluster numbers back to data frame
df_CS$cluster_N = model_k5$cluster

# Based on centers, find which cluster has Months Active around 2.007
model_k5$centers


### HIERARCHICAL CLUSTERING
## Create dendrogram
# Measure distances to feed into hclust()
d = dist(df_CS[, -6])  # Exclude cluster column present

# Using complete linkage approach
model_cmplt = hclust(d, method="complete")

# View the dendrogram
plot(model_cmplt)

# Split results into k=4 clusters using factor(cutree())
hier_clusters = factor(cutree(model_cmplt, k = 4))
df$hclusters = hier_clusters
df_CS$hclusters = hier_clusters


## Boxplots for each variable for each cluster

# First, let's see which clusters we have
table(df$hclusters)

# Boxplots for Cluster 1
boxplot(df[df$hclusters == 1, c("Months Active", "Reviews", "Average Review", "Votes", "Friends")],
        main = "Cluster 1")

# Boxplots for Cluster 2
boxplot(df[df$hclusters == 2, c("Months Active", "Reviews", "Average Review", "Votes", "Friends")],
        main = "Cluster 2")

# Boxplots for Cluster 3
boxplot(df[df$hclusters == 3, c("Months Active", "Reviews", "Average Review", "Votes", "Friends")],
        main = "Cluster 3")

# Boxplots for Cluster 4
boxplot(df[df$hclusters == 4, c("Months Active", "Reviews", "Average Review", "Votes", "Friends")],
        main = "Cluster 4")
R Cluster Analysis and Data Visualization Output
Figure 1: Executing cluster analysis visualizations and profiling outputs in RStudio.

Step-by-Step Explanation of the R Code

1. Data Import & Cleaning

The script reads an Excel dataset (Yelp.xlsx) using readxl::read_excel(). It inspects column data types via str(df) and strips incomplete rows using na.omit(df) to prevent distance calculation errors. nrow(df) counts the clean sample size.

2. Data Standardization with caret

Because K-Means uses Euclidean distance (\(d = \sqrt{\sum (x_i - y_i)^2}\)), variables with large ranges (like Votes or Friends) would dominate small-scale variables (like Average Review). We drop non-numeric ID columns (df[, -1]) and standardize using caret::preProcess(method = c("scale", "center")), centering each variable to mean = 0 and standard deviation = 1.

3. K-Means Modeling (k = 5)

An elbow chart is generated to evaluate total within-cluster sum of squares. kmeans(df_CS, 5) partitions the standardized data into 5 clusters. model_k5$centers reports the 5 cluster centroids, allowing you to identify specific cluster characteristics (such as locating the cluster with standardized Months Active \(\approx 2.007\)).

4. Hierarchical Clustering (hclust complete linkage)

Euclidean pairwise distances are computed with dist(). hclust(d, method="complete") forms a hierarchical tree (dendrogram) using maximum pairwise distance. cutree(model_cmplt, k = 4) cuts the tree into 4 discrete clusters.

5. Cluster Profiling with Boxplots

The script subsets observations by cluster ID (df$hclusters == 1 through 4) and generates boxplots across key variables (Months Active, Reviews, Average Review, Votes, Friends) to visually profile user personas.

Get Help With Your R Machine Learning & Clustering Homework

Guaranteed A or B Grade

We guarantee top marks on R programming code, cluster analysis assignments, and knitted R Markdown reports or full money back.

Executable Code & APA Reports

Receive clean, thoroughly commented .R scripts alongside custom written statistical reports interpreting cluster centroids and dendrogram results.

Get R Programming & Cluster Analysis Assistance Today

Struggling with RStudio code bugs, standardization errors, or dendrogram interpretation? Contact us today for a free quote and let our R experts complete your assignment with guaranteed top grades.

Get Guaranteed R Assignment Help Now