# Step 1: Load the Data and Packages

# Load the packages we need
library(factoextra)  # For making nice cluster visualizations

# Create our customer dataset
demo_customer_text <- "
Age,AnnualIncome,SpendingScore,Savings
25,50000,60,5000
30,60000,70,10000
22,40000,50,2000
45,120000,80,50000
35,75000,65,20000
28,55000,55,8000
40,90000,75,30000
50,150000,85,60000
27,52000,58,7000
33,68000,62,15000
38,85000,68,25000
24,48000,53,4000
41,95000,72,28000
29,60000,60,12000
36,72000,67,18000
32,64000,61,14000
44,100000,78,40000
26,50000,56,6000
39,88000,70,26000
31,63000,63,15000
"

# Convert the text into a data frame R can use
customer_data <- read.csv(text = demo_customer_text, stringsAsFactors = FALSE)

# Look at the first few rows
print("First few customers:")
head(customer_data)

# Get a summary of all the data
print("Summary of customer data:")
summary(customer_data)

# Step 2: Understanding Distance Between Customers

# Calculate how different each customer is from every other customer
customer_distances <- dist(customer_data)

# Look at the first few distances
distance_matrix <- round(as.matrix(customer_distances)[1:6, 1:6], 1)
print("Distance matrix (first 6 customers):")
distance_matrix

# Step 3: K-Means Clustering

# Set a seed so we all get the same results
set.seed(123)

# Group customers into 3 clusters using K-means
kmeans_result <- kmeans(customer_data, centers = 3, nstart = 25)

# See which cluster each customer belongs to
print("Customer cluster assignments:")
kmeans_result$cluster

# Add cluster information to our data
customer_data$Cluster <- kmeans_result$cluster

# Look at the average characteristics of each cluster
print("Average characteristics by cluster:")
aggregate(. ~ Cluster, data = customer_data, mean)

# Create a visualization of the clusters
fviz_cluster(kmeans_result, data = customer_data[,1:4], 
             geom = "point", ellipse.type = "convex",
             main = "Customer Clusters (K-means)")

# Step 4: Interpret the Business Meaning (for K-means result)

# Look at detailed characteristics of each K-means cluster
for(i in 1:3) {
  cat("\n=== CLUSTER", i, "CHARACTERISTICS ===\n")
  cluster_data <- customer_data[customer_data$Cluster == i, ]
  
  cat("Number of customers:", nrow(cluster_data), "\n")
  cat("Average age:", round(mean(cluster_data$Age), 1), "\n")
  cat("Average income: $", round(mean(cluster_data$AnnualIncome), 0), "\n")
  cat("Average spending score:", round(mean(cluster_data$SpendingScore), 1), "\n")
  cat("Average savings: $", round(mean(cluster_data$Savings), 0), "\n")
}

# Step 5: Method 2 – Hierarchical Clustering

# Perform hierarchical clustering
hierarchical_result <- hclust(customer_distances, method = "ward.D2")

# Draw the dendrogram
plot(hierarchical_result, main = "Customer Clustering Tree", 
     xlab = "Customers", ylab = "Distance")

# Highlight 3 main groups on the tree
rect.hclust(hierarchical_result, k = 3, border = "red")

# Get cluster assignments for 3 groups
hierarchical_clusters <- cutree(hierarchical_result, k = 3)
print("Hierarchical cluster assignments:")
hierarchical_clusters
