mydata <- read.csv("customer_segmentation.csv")
# Remove extra spaces from column names
names(mydata) <- trimws(names(mydata))
head(mydata)
## ID CS_helpful Recommend Come_again All_Products Profesionalism Limitation
## 1 1 2 2 2 2 2 2
## 2 2 1 2 1 1 1 1
## 3 3 2 1 1 1 1 2
## 4 4 3 3 2 4 1 2
## 5 5 2 1 3 5 2 1
## 6 6 1 1 3 2 1 1
## Online_grocery delivery Pick_up Find_items other_shops Gender Age Education
## 1 2 3 4 1 2 1 2 2
## 2 2 3 3 1 2 1 2 2
## 3 3 3 2 1 3 1 2 2
## 4 3 3 2 2 2 1 3 5
## 5 2 3 1 2 3 2 4 2
## 6 1 2 1 1 4 1 2 5
dim(mydata)
## [1] 22 15
colSums(is.na(mydata))
## ID CS_helpful Recommend Come_again All_Products
## 0 0 0 0 0
## Profesionalism Limitation Online_grocery delivery Pick_up
## 0 0 0 0 0
## Find_items other_shops Gender Age Education
## 0 0 0 0 0
survey_data <- mydata[, names(mydata) != "ID"]
scaled_data <- scale(survey_data)
customer_distances <- dist(scaled_data)
lab_distances <- dist(as.matrix(customer_distances))
seg.hclust <- hclust(
lab_distances,
method = "complete"
)
plot(
seg.hclust,
labels = mydata$ID,
main = "Customer Segmentation",
xlab = "Respondent ID",
sub = ""
)
rect.hclust(
seg.hclust,
k = 3,
border = 2:4
)

groups.3 <- cutree(seg.hclust, k = 3)
# Number of respondents per cluster
table(groups.3)
## groups.3
## 1 2 3
## 17 2 3
# Percentage of respondents per cluster
round(prop.table(table(groups.3)) * 100, 1)
## groups.3
## 1 2 3
## 77.3 9.1 13.6
split(mydata$ID, groups.3)
## $`1`
## [1] 1 2 3 6 7 8 9 10 11 12 13 14 15 16 17 18 21
##
## $`2`
## [1] 4 22
##
## $`3`
## [1] 5 19 20
cluster_means <- aggregate(
survey_data,
by = list(Cluster = groups.3),
FUN = mean
)
print(round(cluster_means, 2))
## Cluster CS_helpful Recommend Come_again All_Products Profesionalism
## 1 1 1.29 1.12 1.24 1.82 1.24
## 2 2 3.00 2.50 1.50 3.00 1.50
## 3 3 2.33 1.67 2.67 3.00 2.33
## Limitation Online_grocery delivery Pick_up Find_items other_shops Gender Age
## 1 1.35 2.24 2.24 2.71 1.29 2.65 1.18 2.41
## 2 2.00 3.00 3.00 2.50 2.00 1.50 1.00 2.50
## 3 2.00 2.00 3.00 1.00 2.00 3.00 2.00 2.67
## Education
## 1 3.12
## 2 5.00
## 3 2.33
cluster_medians <- aggregate(
survey_data,
by = list(Cluster = groups.3),
FUN = median
)
print(cluster_medians)
## Cluster CS_helpful Recommend Come_again All_Products Profesionalism
## 1 1 1 1.0 1.0 2 1.0
## 2 2 3 2.5 1.5 3 1.5
## 3 3 2 1.0 3.0 3 2.0
## Limitation Online_grocery delivery Pick_up Find_items other_shops Gender Age
## 1 1 2 2 3.0 1 2.0 1 2.0
## 2 2 3 3 2.5 2 1.5 1 2.5
## 3 1 2 3 1.0 2 3.0 2 2.0
## Education
## 1 2
## 2 5
## 3 2
write.csv(
data.frame(ID = mydata$ID, Cluster = groups.3),
"clusterID.csv",
row.names = FALSE
)
write.csv(
cluster_means,
"cluster_means.csv",
row.names = FALSE
)
write.csv(
cluster_medians,
"cluster_medians.csv",
row.names = FALSE
)
# Show where the files were saved
getwd()
## [1] "/cloud/project"