Ivana Tonevska

Clustering

mydata_all <- read.csv("/Users/ivanatonevska/Desktop/marketing_campaign.csv",
                       header = TRUE,
                       sep = "\t")
head(mydata_all)
##     ID Year_Birth  Education Marital_Status Income Kidhome Teenhome Dt_Customer
## 1 5524       1957 Graduation         Single  58138       0        0  04-09-2012
## 2 2174       1954 Graduation         Single  46344       1        1  08-03-2014
## 3 4141       1965 Graduation       Together  71613       0        0  21-08-2013
## 4 6182       1984 Graduation       Together  26646       1        0  10-02-2014
## 5 5324       1981        PhD        Married  58293       1        0  19-01-2014
## 6 7446       1967     Master       Together  62513       0        1  09-09-2013
##   Recency MntWines MntFruits MntMeatProducts MntFishProducts MntSweetProducts
## 1      58      635        88             546             172               88
## 2      38       11         1               6               2                1
## 3      26      426        49             127             111               21
## 4      26       11         4              20              10                3
## 5      94      173        43             118              46               27
## 6      16      520        42              98               0               42
##   MntGoldProds NumDealsPurchases NumWebPurchases NumCatalogPurchases
## 1           88                 3               8                  10
## 2            6                 2               1                   1
## 3           42                 1               8                   2
## 4            5                 2               2                   0
## 5           15                 5               5                   3
## 6           14                 2               6                   4
##   NumStorePurchases NumWebVisitsMonth AcceptedCmp3 AcceptedCmp4 AcceptedCmp5
## 1                 4                 7            0            0            0
## 2                 2                 5            0            0            0
## 3                10                 4            0            0            0
## 4                 4                 6            0            0            0
## 5                 6                 5            0            0            0
## 6                10                 6            0            0            0
##   AcceptedCmp1 AcceptedCmp2 Complain Z_CostContact Z_Revenue Response
## 1            0            0        0             3        11        1
## 2            0            0        0             3        11        0
## 3            0            0        0             3        11        0
## 4            0            0        0             3        11        0
## 5            0            0        0             3        11        0
## 6            0            0        0             3        11        0
colnames(mydata_all)
##  [1] "ID"                  "Year_Birth"          "Education"          
##  [4] "Marital_Status"      "Income"              "Kidhome"            
##  [7] "Teenhome"            "Dt_Customer"         "Recency"            
## [10] "MntWines"            "MntFruits"           "MntMeatProducts"    
## [13] "MntFishProducts"     "MntSweetProducts"    "MntGoldProds"       
## [16] "NumDealsPurchases"   "NumWebPurchases"     "NumCatalogPurchases"
## [19] "NumStorePurchases"   "NumWebVisitsMonth"   "AcceptedCmp3"       
## [22] "AcceptedCmp4"        "AcceptedCmp5"        "AcceptedCmp1"       
## [25] "AcceptedCmp2"        "Complain"            "Z_CostContact"      
## [28] "Z_Revenue"           "Response"
mydata <- mydata_all[ , c("Year_Birth", "Education", "Marital_Status", "Teenhome", "Recency", "MntGoldProds","NumStorePurchases", "NumWebVisitsMonth")]
head(mydata)
##   Year_Birth  Education Marital_Status Teenhome Recency MntGoldProds
## 1       1957 Graduation         Single        0      58           88
## 2       1954 Graduation         Single        1      38            6
## 3       1965 Graduation       Together        0      26           42
## 4       1984 Graduation       Together        0      26            5
## 5       1981        PhD        Married        0      94           15
## 6       1967     Master       Together        1      16           14
##   NumStorePurchases NumWebVisitsMonth
## 1                 4                 7
## 2                 2                 5
## 3                10                 4
## 4                 4                 6
## 5                 6                 5
## 6                10                 6
nrow(mydata)
## [1] 2240
colnames(mydata)
## [1] "Year_Birth"        "Education"         "Marital_Status"   
## [4] "Teenhome"          "Recency"           "MntGoldProds"     
## [7] "NumStorePurchases" "NumWebVisitsMonth"

Explanation of the dataset ‘Customer Personality Analysis’:

- Source: Customer Personality Analysis. (2021, August 22). Kaggle. https://www.kaggle.com/datasets/imakash3011/customer-personality-analysis
- Unit of obesrvation: one customer
- Sample size: 2240 customers
- 6 variables:
  * Year_Birth: Customer's birth year (numerical)
  * Education: Customer's education level (categorical, ordinal)
  * Marital_Status: Customer's marital status (categorical)
  * Teenhome: Number of teenagers in customer's household (numerical, ratio)
  * Recency: Number of days since customer's last purchase (numerical)
  * MntGoldProds: Amount spent on gold in last 2 years, in EUR (numerical, ratio)
  * NumStorePurchases: Number of purchases made directly in stores (numerical, ratio)
  * NumWebVisitsMonth: Number of visits to company’s website in the last month (numerical, ratio)
RQ: Check if the customers can be grouped into homogeneous groups based on the 5 cluster variables in order to better understand their purchasing habbits for gold products.
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
mydata <- mydata %>% 
  mutate(id = seq(length.out = n())) %>%
  select(id, everything())
# adding an ID column as first column in the dataset
head(mydata)
##   id Year_Birth  Education Marital_Status Teenhome Recency MntGoldProds
## 1  1       1957 Graduation         Single        0      58           88
## 2  2       1954 Graduation         Single        1      38            6
## 3  3       1965 Graduation       Together        0      26           42
## 4  4       1984 Graduation       Together        0      26            5
## 5  5       1981        PhD        Married        0      94           15
## 6  6       1967     Master       Together        1      16           14
##   NumStorePurchases NumWebVisitsMonth
## 1                 4                 7
## 2                 2                 5
## 3                10                 4
## 4                 4                 6
## 5                 6                 5
## 6                10                 6
unique(mydata$Education)
## [1] "Graduation" "PhD"        "Master"     "Basic"      "2n Cycle"
unique(mydata$Marital_Status)
## [1] "Single"   "Together" "Married"  "Divorced" "Widow"    "Alone"    "Absurd"  
## [8] "YOLO"
mydata$Education <- factor(mydata$Education,
                             levels = c("Graduation", "PhD", "Master", "Basic", "2n Cycle"),
                             labels = c("Grad", "PhD", "MA", "Basic", "2nCycle"))
mydata$Marital_Status <- factor(mydata$Marital_Status,
                             levels = c("Together", "Married", "Divorced", "Widow", "Alone", "Absurd", "YOLO"),
                             labels = c("Together", "Married", "Divorced", "Widow", "Alone", "Absurd", "YOLO"))

Descriptive statistics for the whole sample

summary(mydata[ ,-1])
##    Year_Birth     Education     Marital_Status    Teenhome         Recency     
##  Min.   :1893   Grad   :1127   Married :864    Min.   :0.0000   Min.   : 0.00  
##  1st Qu.:1959   PhD    : 486   Together:580    1st Qu.:0.0000   1st Qu.:24.00  
##  Median :1970   MA     : 370   Divorced:232    Median :0.0000   Median :49.00  
##  Mean   :1969   Basic  :  54   Widow   : 77    Mean   :0.5062   Mean   :49.11  
##  3rd Qu.:1977   2nCycle: 203   Alone   :  3    3rd Qu.:1.0000   3rd Qu.:74.00  
##  Max.   :1996                  (Other) :  4    Max.   :2.0000   Max.   :99.00  
##                                NA's    :480                                    
##   MntGoldProds    NumStorePurchases NumWebVisitsMonth
##  Min.   :  0.00   Min.   : 0.00     Min.   : 0.000   
##  1st Qu.:  9.00   1st Qu.: 3.00     1st Qu.: 3.000   
##  Median : 24.00   Median : 5.00     Median : 6.000   
##  Mean   : 44.02   Mean   : 5.79     Mean   : 5.317   
##  3rd Qu.: 56.00   3rd Qu.: 8.00     3rd Qu.: 7.000   
##  Max.   :362.00   Max.   :13.00     Max.   :20.000   
## 
  • Year_Birth 3rd Qu=1997: 75% of the customers were born before, or exactly in, 1977.
  • MntGoldProds Max=362: The most a household has spent on gold products was 362EUR.
  • NumWebVisitsMonth Median=6: Half (50%) of the customers visit the website up to, or exactly, 6 times per month, while the other half (50%) visit it more than 6 times on a monthly basis.

Making a random smaple of 500 units for the purposes of clustering

set.seed(1)
sample_data <- mydata[sample(nrow(mydata), 500), ]
summary(sample_data)
##        id           Year_Birth     Education    Marital_Status    Teenhome    
##  Min.   :   5.0   Min.   :1899   Grad   :247   Married :193    Min.   :0.000  
##  1st Qu.: 510.8   1st Qu.:1959   PhD    :121   Together:122    1st Qu.:0.000  
##  Median :1104.0   Median :1970   MA     : 79   Divorced: 62    Median :0.000  
##  Mean   :1097.5   Mean   :1968   Basic  : 13   Widow   : 17    Mean   :0.522  
##  3rd Qu.:1659.5   3rd Qu.:1976   2nCycle: 40   Alone   :  1    3rd Qu.:1.000  
##  Max.   :2231.0   Max.   :1995                 (Other) :  1    Max.   :2.000  
##                                                NA's    :104                   
##     Recency       MntGoldProds    NumStorePurchases NumWebVisitsMonth
##  Min.   : 0.00   Min.   :  0.00   Min.   : 0.000    Min.   : 0.000   
##  1st Qu.:23.00   1st Qu.:  8.75   1st Qu.: 3.000    1st Qu.: 3.000   
##  Median :49.00   Median : 24.00   Median : 5.000    Median : 5.000   
##  Mean   :49.65   Mean   : 45.67   Mean   : 5.944    Mean   : 5.166   
##  3rd Qu.:77.00   3rd Qu.: 64.00   3rd Qu.: 8.000    3rd Qu.: 7.000   
##  Max.   :99.00   Max.   :249.00   Max.   :13.000    Max.   :13.000   
## 

(The categorical variables are already transformed to factors and some explanations of the descriptive statistics are shown above for the whole sample)

Standardization of the cluster variables

sample_data$Teenhome_z <- scale(sample_data$Teenhome)
sample_data$Recency_z <- scale(sample_data$Recency)
sample_data$MntGoldProds_z <- scale(sample_data$MntGoldProds)
sample_data$NumStorePurchases_z <- scale(sample_data$NumStorePurchases)
sample_data$NumWebVisitsMonth_z <- scale(sample_data$NumWebVisitsMonth)
#install.packages("Hmisc")
library(Hmisc)
## 
## Attaching package: 'Hmisc'
## The following objects are masked from 'package:dplyr':
## 
##     src, summarize
## The following objects are masked from 'package:base':
## 
##     format.pval, units

Correlation between the cluster variables

rcorr(as.matrix(sample_data[ , c("Teenhome", "Recency", "MntGoldProds","NumStorePurchases", "NumWebVisitsMonth")]),
      type = "pearson")
##                   Teenhome Recency MntGoldProds NumStorePurchases
## Teenhome              1.00    0.04        -0.06              0.07
## Recency               0.04    1.00         0.05              0.04
## MntGoldProds         -0.06    0.05         1.00              0.42
## NumStorePurchases     0.07    0.04         0.42              1.00
## NumWebVisitsMonth     0.13    0.01        -0.25             -0.43
##                   NumWebVisitsMonth
## Teenhome                       0.13
## Recency                        0.01
## MntGoldProds                  -0.25
## NumStorePurchases             -0.43
## NumWebVisitsMonth              1.00
## 
## n= 500 
## 
## 
## P
##                   Teenhome Recency MntGoldProds NumStorePurchases
## Teenhome                   0.4146  0.1878       0.1098           
## Recency           0.4146           0.2936       0.3518           
## MntGoldProds      0.1878   0.2936               0.0000           
## NumStorePurchases 0.1098   0.3518  0.0000                        
## NumWebVisitsMonth 0.0031   0.8489  0.0000       0.0000           
##                   NumWebVisitsMonth
## Teenhome          0.0031           
## Recency           0.8489           
## MntGoldProds      0.0000           
## NumStorePurchases 0.0000           
## NumWebVisitsMonth
  • The correlations between the cluster variables are low (<0.3) which is good, since we need low correlation between them to perform clustering.

Finding Outliers through dissimilarity

sample_data$Dissimilarity <- sqrt(sample_data$Teenhome_z^2 + sample_data$Recency_z^2 + sample_data$MntGoldProds_z^2 + sample_data$NumStorePurchases_z^2 + sample_data$NumWebVisitsMonth_z)
## Warning in sqrt(sample_data$Teenhome_z^2 + sample_data$Recency_z^2 +
## sample_data$MntGoldProds_z^2 + : NaNs produced
head(sample_data[order(-sample_data$Dissimilarity), c("id", "Dissimilarity") ], 10)
##        id Dissimilarity
## 1642 1642      4.179772
## 1326 1326      4.012678
## 724   724      3.973150
## 2034 2034      3.799494
## 1744 1744      3.794877
## 1474 1474      3.761280
## 99     99      3.734258
## 2094 2094      3.642178
## 369   369      3.639319
## 464   464      3.594791
#10 units with the highest value of dissimilarity
sample_data <- sample_data %>%
  filter(!id %in% c(1642, 1326, 724))
  • Units with ID 1642, 1326 and 724 were removed as outliers due to higher values of dissimilarity, therefore the standardization should be repeated.
sample_data$Teenhome_z <- scale(sample_data$Teenhome)
sample_data$Recency_z <- scale(sample_data$Recency)
sample_data$MntGoldProds_z <- scale(sample_data$MntGoldProds)
sample_data$NumStorePurchases_z <- scale(sample_data$NumStorePurchases)
sample_data$NumWebVisitsMonth_z <- scale(sample_data$NumWebVisitsMonth)

Calculating Euclidian Distances

#install.packages("factoextra")
library(factoextra)
## Loading required package: ggplot2
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
distance <- get_dist(sample_data[c("Teenhome_z", "Recency_z", "MntGoldProds_z", "NumStorePurchases_z", "NumWebVisitsMonth_z")],
                     method = "euclidian")

distance2 <- distance^2

fviz_dist(distance2) #Dissimilarity matrix

* The dissimilarity matrix in the output above shows all the distances between all pairs of units * Dimension of the dissimilarity matrix: nxn (497 x 497) * Main diagonal: 0 * Outside the main diagonal: pairwise distances

Hopkins Statistics

Checking if the data is suitable (if natural groups are forming)
get_clust_tendency(sample_data[c("Teenhome_z", "Recency_z", "MntGoldProds_z", "NumStorePurchases_z", "NumWebVisitsMonth_z")],
                   n = nrow(sample_data) - 1,
                   graph = FALSE)
## $hopkins_stat
## [1] 0.7341948
## 
## $plot
## NULL
  • As the result is higher than 0.5, which is the treshold for the Hopkins statistic, the data is suitable and there are natural groups.

Hierarchical clustering based on Ward’s algorithm and Squared Euclidian Distance

#install.packages("dplyr")
library(dplyr)
library(factoextra)
WARD <- sample_data[c("Teenhome_z", "Recency_z", "MntGoldProds_z", "NumStorePurchases_z", "NumWebVisitsMonth_z")] %>%
  get_dist(method = "euclidean") %>% #selecting distance
  hclust(method = "ward.D2") #selecting algorithm

WARD
## 
## Call:
## hclust(d = ., method = "ward.D2")
## 
## Cluster method   : ward.D2 
## Distance         : euclidean 
## Number of objects: 497
  • Ward’s algorithm minimizes the sum of squares within groups, so that we would be able to make as homogeneous groups as possible.
  • Ward’s algorithm should always be used with Squared Euclidian Distance

Dendrogram

library(factoextra)

fviz_dend(WARD)
## Warning: The `<scale>` argument of `guides()` cannot be `FALSE`. Use "none" instead as
## of ggplot2 3.3.4.
## ℹ The deprecated feature was likely used in the factoextra package.
##   Please report the issue at <https://github.com/kassambara/factoextra/issues>.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

fviz_dend(WARD,
          k = 3,
          cex = 0.5,
          palette = "jama",
          color_labels_by_k = TRUE,
          rect = TRUE)

Cutting the dendrogram into 3 clusters

sample_data$ClusterWard <- cutree(WARD,
                             k = 3)

head(sample_data[ ,c("id","ClusterWard")])
##     id ClusterWard
## 1 1017           1
## 2  679           2
## 3 2177           1
## 4  930           1
## 5 1533           1
## 6  471           1

Calculating the positions of the initial leaders

Initial_leaders <- aggregate(sample_data[ , c("Teenhome_z", "Recency_z", "MntGoldProds_z", "NumStorePurchases_z", "NumWebVisitsMonth_z")],
                             by = list(sample_data$ClusterWard),
                             FUN = mean)

Initial_leaders
##   Group.1 Teenhome_z   Recency_z MntGoldProds_z NumStorePurchases_z
## 1       1 -0.2451422 -0.03333107      0.5846954           0.7751150
## 2       2 -0.9314239 -0.05487891     -0.5342178          -0.8083360
## 3       3  1.0310420  0.08636445     -0.3923298          -0.4449977
##   NumWebVisitsMonth_z
## 1          -0.7368195
## 2           0.7917964
## 3           0.4054641
  • Since the dendrogram is cut 3 times, we need 3 initial leaders to preforming K-means clustering
  • Each centroid has 5 elements (as there are 5 cluster variables)

Performing K-Means clustering

library(factoextra)

K_MEANS <- hkmeans(sample_data[ , c("Teenhome_z", "Recency_z", "MntGoldProds_z", "NumStorePurchases_z", "NumWebVisitsMonth_z")],
                   k = 3,
                   hc.metric = "euclidean",
                   hc.method = "ward.D2")

K_MEANS
## Hierarchical K-means clustering with 3 clusters of sizes 174, 138, 185
## 
## Cluster means:
##   Teenhome_z   Recency_z MntGoldProds_z NumStorePurchases_z NumWebVisitsMonth_z
## 1 -0.3436508  0.09759390      0.7909515           0.9288328          -0.8701363
## 2 -0.9184220 -0.10466768     -0.5095627          -0.7854176           0.6702177
## 3  1.0083107 -0.01371459     -0.3638157          -0.2877258           0.3184523
## 
## Clustering vector:
##   [1] 1 2 1 3 1 1 2 3 2 2 3 2 3 3 1 1 2 3 2 2 2 1 2 1 3 1 3 3 2 3 3 2 1 1 3 1 2
##  [38] 2 2 2 2 1 2 3 2 3 2 2 3 2 2 2 3 1 1 1 1 3 2 2 1 3 1 1 1 1 3 3 3 1 1 1 2 3
##  [75] 3 2 3 3 1 1 2 2 3 1 3 1 1 2 1 1 3 1 2 3 2 3 1 2 1 2 2 1 3 3 1 1 3 2 1 3 3
## [112] 1 3 3 1 3 3 1 3 1 3 3 3 1 3 1 1 3 1 2 2 2 1 1 2 2 1 3 1 3 3 1 2 1 1 1 2 3
## [149] 2 1 3 3 3 2 1 1 3 3 1 3 2 2 1 3 2 3 3 2 2 1 1 3 1 2 1 3 1 2 3 2 3 3 1 2 2
## [186] 1 3 3 3 3 2 3 1 2 2 3 1 3 3 1 3 3 1 3 1 2 3 3 3 1 3 3 1 2 2 1 3 1 3 2 1 1
## [223] 2 1 1 2 3 3 2 3 3 1 2 3 1 3 2 3 2 3 1 2 1 1 3 1 3 3 1 2 1 3 2 2 3 2 3 3 3
## [260] 1 3 3 3 3 2 2 3 1 1 1 2 2 1 3 3 3 2 1 3 2 3 1 2 3 1 3 3 3 1 3 1 3 3 1 1 3
## [297] 3 3 1 1 3 2 2 3 2 3 2 3 2 2 1 1 3 3 3 1 3 3 1 3 2 1 1 2 1 3 2 1 1 1 2 1 1
## [334] 3 2 1 1 1 1 3 3 3 2 1 2 3 3 3 3 1 3 1 2 1 3 2 1 1 3 1 2 3 1 1 3 2 1 1 1 2
## [371] 3 2 2 1 1 2 1 3 1 2 2 3 2 1 2 3 2 3 3 2 1 1 2 2 3 2 1 1 1 1 1 2 3 3 3 3 3
## [408] 1 2 3 3 2 1 3 2 1 1 3 3 3 3 3 2 3 2 3 1 1 3 1 1 1 1 2 3 2 3 2 2 1 2 1 3 3
## [445] 2 3 2 2 3 1 2 1 1 1 3 2 1 3 3 2 1 1 3 1 1 3 1 2 3 1 1 1 2 2 2 3 1 3 2 1 3
## [482] 2 1 2 1 3 1 3 2 2 3 3 1 1 3 2 3
## 
## Within cluster sum of squares by cluster:
## [1] 765.8729 268.5847 485.0733
##  (between_SS / total_SS =  38.7 %)
## 
## Available components:
## 
##  [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
##  [6] "betweenss"    "size"         "iter"         "ifault"       "data"        
## [11] "hclust"
  • Sizes of the clusters:

  • 1st cluster: 174 units (35% of total)

  • 2nd cluster: 138 (27.8% of total)

  • 3rd cluster: 185 (37.2% of total)

  • When comparing the positions of the initial and final leaders, we can see differences, meaning that there were some reclassifications of units

  • Cluster vector: shows in which cluster is each unit

  • Within cluster sum of squares by cluster shows how much variability there is in each group

  • Between_SS/total_SS = 38.7%: the higher this ratio is (preferrably 50%), the lower the sum of squares within the groups will be (homogeneous groups are made)

  • Even though the ratio is not high enough and maybe we should consider using different cluster variables, I will continue with the cluster analysis for educational purposes.

Cluster Plot

fviz_cluster(K_MEANS,
             palette = 'jama',
             repel = FALSE,
             ggtheme = theme_classic())

* From the cluster plot, we can say that unit 59 might also be an outlier but I will leave it for now.

sample_data$ClusterK_Means <- K_MEANS$cluster
head(sample_data[, c("id", "ClusterWard", "ClusterK_Means")])
##     id ClusterWard ClusterK_Means
## 1 1017           1              1
## 2  679           2              2
## 3 2177           1              1
## 4  930           1              3
## 5 1533           1              1
## 6  471           1              1
table(sample_data$ClusterWard)
## 
##   1   2   3 
## 217 120 160
table(sample_data$ClusterK_Means)
## 
##   1   2   3 
## 174 138 185
table(sample_data$ClusterWard, sample_data$ClusterK_Means)
##    
##       1   2   3
##   1 172  17  28
##   2   0 120   0
##   3   2   1 157
  • Fist there were 217 units in group 1, after performing K-Means clustering, 2 units were reclassified from group 3 to group 1, 17 units from group 1 to group 2 and 28 units from group 1 to group 3.
  • Fist there were 120 units in group 2, after performing K-Means clustering, 17 units were reclassified from group 1 to group 2, while 1 unit was reclasssified from group 3 to group 2.
  • Fist there were 160 units in group 3, after performing K-Means clustering, 28 units were reclassified from group 1 to group 3, 2 units from group 3 to group 1 and 1 unit from group 3 to group 2 .

Final leaders (Centroids)

Centroids <- K_MEANS$centers
round(Centroids,3)
##   Teenhome_z Recency_z MntGoldProds_z NumStorePurchases_z NumWebVisitsMonth_z
## 1     -0.344     0.098          0.791               0.929              -0.870
## 2     -0.918    -0.105         -0.510              -0.785               0.670
## 3      1.008    -0.014         -0.364              -0.288               0.318
#install.packages("ggplot2")
library(ggplot2)
#install.packages("tidyr")
library(tidyr)
Figure <- as.data.frame(Centroids)
Figure$id <- 1:nrow(Figure)
Figure <- pivot_longer(Figure, cols = c("Teenhome_z", "Recency_z", "MntGoldProds_z", "NumStorePurchases_z", "NumWebVisitsMonth_z"))

Figure$Groups <- factor(Figure$id,
                        levels = c(1, 2, 3, 4, 5),
                        labels = c("1", "2", "3", "4", "5"))

Figure$NameFactor <- factor(Figure$name,
                            levels = c("Teenhome_z", "Recency_z", "MntGoldProds_z", "NumStorePurchases_z", "NumWebVisitsMonth_z"),
                            labels = c("Teenhome_z", "Recency_z", "MntGoldProds_z", "NumStorePurchases_z", "NumWebVisitsMonth_z"))

ggplot(Figure, aes(x = NameFactor, y = value)) +
  geom_hline(yintercept = 0) +
  theme_bw() +
  geom_point(aes(shape = Groups, col = Groups), size = 3) +
  geom_line(aes(group = id), linewidth = 1) +
  ylab("Averages") +
  xlab("Cluster Variables") +
  ylim(-1.5, 1.5)

As the 0 on the graph represents the average, we can say that the households in groups 1 and 2 have less teenage kids compared to the average, while those in group 3 have more than average. Regarding the number of days since customer’s last purchase, the units of all three groups are close to the average. Additionally, custoemrs from group 1 in the last 2 years spent the most on gold products (above average), and had the highest number of purchases in the store when compared to the other two groups. On the other hand, customers from group 2 during the last month visited the website more than the average number of monthly visits, and more than group 1 & 3.

Performing ANOVAs (checking if the cluster variabels successfully calssified the units into groups)

fit <- aov(cbind(Teenhome_z, Recency_z, MntGoldProds_z, NumStorePurchases_z, NumWebVisitsMonth_z) ~ as.factor(ClusterK_Means),
           data = sample_data)
summary(fit)
##  Response 1 :
##                            Df Sum Sq Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means)   2 325.04 162.520  469.61 < 2.2e-16 ***
## Residuals                 494 170.96   0.346                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
##  Response 2 :
##                            Df Sum Sq Mean Sq F value Pr(>F)
## as.factor(ClusterK_Means)   2    3.2 1.60195  1.6059 0.2018
## Residuals                 494  492.8 0.99756               
## 
##  Response 3 :
##                            Df Sum Sq Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means)   2 169.17  84.587  127.85 < 2.2e-16 ***
## Residuals                 494 326.83   0.662                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
##  Response 4 :
##                            Df Sum Sq Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means)   2 250.56 125.280  252.15 < 2.2e-16 ***
## Residuals                 494 245.44   0.497                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
##  Response 5 :
##                            Df Sum Sq Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means)   2 212.49 106.246  185.13 < 2.2e-16 ***
## Residuals                 494 283.51   0.574                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
  • Since there are 5 cluster variable, we are doing 5 ANOVAs. The goal of this is to reject H0 for all cluster variables, meaning that the choice of the cluster variables was correct. (Assuming all assumptions for ANOVA are met) H0: μ1 = μ2 = μ3 (μ i same in all 3 groups) H1: At least one μ is different.
  • BSD we do not have enough evidence to reject all H0.
  • We cannot say that the arithmetic mean for ‘Recency’ is different in at least one group (cannot claim that there are statistically signifficant differences between the three groups regarding ‘Recency’).
  • The variable should be eliminated or removed and the classification should be repeated.
fit1 <- aov(cbind(Teenhome_z, MntGoldProds_z, NumStorePurchases_z, NumWebVisitsMonth_z) ~ as.factor(ClusterK_Means),
           data = sample_data)
summary(fit1)
##  Response 1 :
##                            Df Sum Sq Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means)   2 325.04 162.520  469.61 < 2.2e-16 ***
## Residuals                 494 170.96   0.346                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
##  Response 2 :
##                            Df Sum Sq Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means)   2 169.17  84.587  127.85 < 2.2e-16 ***
## Residuals                 494 326.83   0.662                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
##  Response 3 :
##                            Df Sum Sq Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means)   2 250.56 125.280  252.15 < 2.2e-16 ***
## Residuals                 494 245.44   0.497                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
##  Response 4 :
##                            Df Sum Sq Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means)   2 212.49 106.246  185.13 < 2.2e-16 ***
## Residuals                 494 283.51   0.574                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

H0: μ1 = μ2 = μ3 (μ i same in all 3 groups) H1: At least one μ is different. In this case we can reject H0 for all 4 tests (p<0.001) and conclude that all cluster variables stat. signif. differentiate between the groups.

Validation

Validating the clusters with the following demographics:

Age (ANOVA)
aggregate(sample_data$Year_Birth,
          by = list(sample_data$ClusterK_Means),
          FUN = "mean")
##   Group.1        x
## 1       1 1966.983
## 2       2 1976.181
## 3       3 1964.211
  • H0: μ ageG1 = μ ageG2 = μ ageG3
  • H1: At least one μageG is different
fit <- aov(Year_Birth ~ as.factor(ClusterK_Means),
           data = sample_data)
summary(fit)
##                            Df Sum Sq Mean Sq F value Pr(>F)    
## as.factor(ClusterK_Means)   2  11946    5973   47.55 <2e-16 ***
## Residuals                 494  62058     126                   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
  • We reject H0 at p<0.001 and can claim that at least one μ age differs. (we can validate the clustering with age)
Education (Chi-squared test)
chisq_results <- chisq.test(sample_data$Education, as.factor(sample_data$ClusterK_Means))
## Warning in chisq.test(sample_data$Education,
## as.factor(sample_data$ClusterK_Means)): Chi-squared approximation may be
## incorrect
chisq_results
## 
##  Pearson's Chi-squared test
## 
## data:  sample_data$Education and as.factor(sample_data$ClusterK_Means)
## X-squared = 42.787, df = 8, p-value = 9.632e-07
  • H0: There is no association between the categorical variables
  • H1: There is association between the variables
addmargins(chisq_results$observed)
##                      
## sample_data$Education   1   2   3 Sum
##               Grad     98  68  80 246
##               PhD      36  26  58 120
##               MA       23  18  37  78
##               Basic     1  12   0  13
##               2nCycle  16  14  10  40
##               Sum     174 138 185 497
# observed frequencies
round(chisq_results$expected, 2)
##                      
## sample_data$Education     1     2     3
##               Grad    86.12 68.31 91.57
##               PhD     42.01 33.32 44.67
##               MA      27.31 21.66 29.03
##               Basic    4.55  3.61  4.84
##               2nCycle 14.00 11.11 14.89
#expected frequencies
  • 3 of the expected frquencies are less than 5 but that will not be a problem since in larger contingency tables, up to 20% of the expected frequencies can be between 1 & 5. However, this will reduce the power of the test.
round(chisq_results$res, 2)
##                      
## sample_data$Education     1     2     3
##               Grad     1.28 -0.04 -1.21
##               PhD     -0.93 -1.27  1.99
##               MA      -0.82 -0.79  1.48
##               Basic   -1.66  4.42 -2.20
##               2nCycle  0.53  0.87 -1.27
#standardized residuals 
  • We can reject H0 at p<0.001 and claim there is a stat.signif. association between the education and the clustering groups. (we can validate the clustering with Education)
  • There are less than expected customers with masters degree in the second group (𝛼= 0.05).
Marital status (Chi-squared test)
chisq_results1 <- chisq.test(sample_data$Marital_Status, as.factor(sample_data$ClusterK_Means))
## Warning in chisq.test(sample_data$Marital_Status,
## as.factor(sample_data$ClusterK_Means)): Chi-squared approximation may be
## incorrect
chisq_results1
## 
##  Pearson's Chi-squared test
## 
## data:  sample_data$Marital_Status and as.factor(sample_data$ClusterK_Means)
## X-squared = 9.3467, df = 10, p-value = 0.4995
  • H0: There is no association between the categorical variables
  • H1: There is association between the variables
addmargins(chisq_results1$observed)
##                           
## sample_data$Marital_Status   1   2   3 Sum
##                   Together  49  28  45 122
##                   Married   62  55  74 191
##                   Divorced  22  15  24  61
##                   Widow      8   1   8  17
##                   Alone      0   0   1   1
##                   Absurd     1   0   0   1
##                   Sum      142  99 152 393
# observed frequencies
round(chisq_results1$expected, 2)
##                           
## sample_data$Marital_Status     1     2     3
##                   Together 44.08 30.73 47.19
##                   Married  69.01 48.11 73.87
##                   Divorced 22.04 15.37 23.59
##                   Widow     6.14  4.28  6.58
##                   Alone     0.36  0.25  0.39
##                   Absurd    0.36  0.25  0.39
#expected frequencies
round(chisq_results1$res, 2)
##                           
## sample_data$Marital_Status     1     2     3
##                   Together  0.74 -0.49 -0.32
##                   Married  -0.84  0.99  0.01
##                   Divorced -0.01 -0.09  0.08
##                   Widow     0.75 -1.59  0.56
##                   Alone    -0.60 -0.50  0.99
##                   Absurd    1.06 -0.50 -0.62
#standardized residuals 
  • We do not have enough evidence to reject H0 and claim that there is association between the clusters and marital status. (We cannot validate the data with marital status)

Conclusion

Classification of 500 random customers was based on 5 standardized variables. For hierarchical clustering, I used Ward’s algorithm, and based on the analysis of the dendrogram I decided to classify the customers into 3 groups. I further optimized the classification using the K-Means cluster. Group 1 is the second largest group, with 174 customers (35%), characterised by lower than average value for number of teenage kids and monthly website visits, but higher than average amount spent on gold products in the last two years and number of products purchased in physical store.These customers have spent the most on gold products compared to the other two groups. On average, these customers are close to the average age of all clients. There are less then expected customers with PhD in the group (𝛼= 0.05). (eg. for further marketing purposes): Based on this random sample and the cluster analysis, we can say that those who visit the company’s website less often tend to spend more money on gold products in physical stores, while those who spend more time on the website, spend less than the average amount spent on gold in two years.