Homework 4

Saša Kočar

Data set

This data set was retrieved from Kaggle.com. Wholesale customers Data Set. (https://www.kaggle.com/datasets/binovi/wholesale-customers-data-set)

The dataset refers to clients of a wholesale distributor. It includes the annual spending in monetary units (m.u.) on diverse product categories.

library(readr)
mydata <- read_csv("~/Desktop/IMB/Bootcamp/R studio/class work/Wholesale customers data.csv")
## Rows: 440 Columns: 8
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (8): Channel, Region, Fresh, Milk, Grocery, Frozen, Detergents_Paper, De...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
mydata <- cbind(ID = 1:nrow(mydata), mydata)
mydata <- mydata[, -c(4, 6, 8)]
head(mydata)
##   ID Channel Region Milk Frozen Delicassen
## 1  1       2      3 9656    214       1338
## 2  2       2      3 9810   1762       1776
## 3  3       2      3 8808   2405       7844
## 4  4       1      3 1196   6404       1788
## 5  5       2      3 5410   3915       5185
## 6  6       2      3 8259    666       1451

Description of data:

Channel: 1 - Horeca (Hotel/Restaurant/Cafe), 2 - Retail channel

Region: 1 - Lisnon, 2- Oporto or 3 - Other.

Milk: annual spending (m.u.) on milk products

Frozen: annual spending (m.u.) on frozen products

Delicassen: annual spending (m.u.) on and delicatessen products.

mydata$ChannelF <- factor(mydata$Channel,
                         levels = c("1", "2"),
                         labels = c("horeca", "retail"))
mydata$RegionF <- factor(mydata$Region,
                         levels = c("1", "2", "3"),
                         labels = c("Lisnon", "Oporto","Other"))

#Standardisation
mydata$Milk_z <- scale(mydata$Milk)
mydata$Frozen_z <- scale(mydata$Frozen)
mydata$Delicassen_z <- scale(mydata$Delicassen)

I standardised variables, so they will all contribute the same.

library(Hmisc)
## 
## Attaching package: 'Hmisc'
## The following objects are masked from 'package:base':
## 
##     format.pval, units
rcorr(as.matrix(mydata[ , c("Milk_z", "Frozen_z", "Delicassen_z")]),
      type = "pearson")
##              Milk_z Frozen_z Delicassen_z
## Milk_z         1.00     0.12         0.41
## Frozen_z       0.12     1.00         0.39
## Delicassen_z   0.41     0.39         1.00
## 
## n= 440 
## 
## 
## P
##              Milk_z Frozen_z Delicassen_z
## Milk_z              0.0092   0.0000      
## Frozen_z     0.0092          0.0000      
## Delicassen_z 0.0000 0.0000

We check correlation matrix for our chosen variables. Correalation for clustering should be low, therefore we can perform clustering.

mydata$Dissimilarity <- sqrt(mydata$Milk_z^2 + mydata$Frozen_z^2 + mydata$Delicassen_z^2 )
head(mydata[order(-mydata$Dissimilarity), ], 15)
##      ID Channel Region  Milk Frozen Delicassen ChannelF RegionF     Milk_z
## 184 184       1      3 43950  36534      47943   horeca   Other  5.1696185
## 326 326       1      2 16784  60869       5609   horeca  Oporto  1.4887768
## 87   87       2      3 73498    987        903   retail   Other  9.1732079
## 48   48       2      3 54259   7782       6465   retail   Other  6.5664305
## 24   24       2      3 36423   5154      16523   retail   Other  4.1497519
## 94   94       1      3  3090  35009       2698   horeca   Other -0.3666840
## 86   86       2      3 46197   1026       2944   retail   Other  5.4740744
## 182 182       1      3 29627  16745       8550   horeca   Other  3.2289317
## 72   72       1      3  1266   5373      14472   horeca   Other -0.6138258
## 88   88       1      3  5025   6312      14351   horeca   Other -0.1045022
## 62   62       2      3 38369   3254       2017   retail   Other  4.4134240
## 57   57       2      3 29892   2616       1340   retail   Other  3.2648378
## 197 197       1      1  7209  18711       2876   horeca  Lisnon  0.1914176
## 172 172       2      3 25862    651       6250   retail   Other  2.7187952
## 93   93       2      3 27472   3232       5130   retail   Other  2.9369412
##        Frozen_z Delicassen_z Dissimilarity
## 184  6.89275382  16.45971129     18.578404
## 326 11.90544950   1.44821848     12.085260
## 87  -0.42946902  -0.22051315      9.185903
## 48   0.97021321   1.75175318      6.864981
## 24   0.42887915   5.31828587      6.759330
## 94   6.57862352   0.41598776      6.601954
## 86  -0.42143553   0.50321852      5.513286
## 182  2.81647543   2.49108711      4.956213
## 72   0.47399032   4.59100822      4.656050
## 88   0.66741219   4.54810203      4.597999
## 62   0.03750369   0.17450747      4.417032
## 57  -0.09391607  -0.06555444      3.266846
## 197  3.22144604   0.47910595      3.262499
## 172 -0.49868068   1.67551491      3.232318
## 93   0.03297198   1.27836671      3.203269

All those are candidates for being an outlier, the furthest away.

library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:Hmisc':
## 
##     src, summarize
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
mydata <- mydata %>%
  filter (!ID %in% c(184, 326, 87, 48, 24, 94, 86))

I decided to remove those units, because they are the furthest away.

#After removing units we have to standardize again
mydata$Milk_z <- scale(mydata$Milk)
mydata$Frozen_z <- scale(mydata$Frozen)
mydata$Delicassen_z <- scale(mydata$Delicassen)
library(factoextra)
## Loading required package: ggplot2
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
#Calculating Euclidean distances
distance <- get_dist(mydata[c("Milk_z", "Frozen_z", "Delicassen_z")],
                     method = "euclidian")

distance2 <- distance^2
fviz_dist(distance2) #showing dissimilarity matrix

get_clust_tendency(mydata[c("Milk_z", "Frozen_z", "Delicassen_z")], #Hopkins statistics
                   n = nrow(mydata) -1,
                   graph = FALSE)
## $hopkins_stat
## [1] 0.8972819
## 
## $plot
## NULL

Hopkins statistics is above 0,5, which means data is clusterable.

library(dplyr)
WARD <- mydata[c("Milk_z", "Frozen_z", "Delicassen_z")] %>%
  scale() %>%
  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: 433

Since we have 433 unit, we know it was needed 432 steps to unify all units into 1 group.

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.

#### Based on the dendrogram 3 clusters seem to be the most appropriate, but they are not the best in terms of heterogeneity.

fviz_dend(WARD,
          k = 3,
          cex = 0.5)

mydata$ClassificationWARD <-cutree(WARD,
                                   k = 3)
head(mydata[, c("ID", "ClassificationWARD")])
##   ID ClassificationWARD
## 1  1                  1
## 2  2                  1
## 3  3                  2
## 4  4                  3
## 5  5                  2
## 6  6                  1

Based on hierarchical classification ID 1 belongs to group 1, ID 5 to group 2 and ID 4 to group 3.

Initialleaders <- aggregate(mydata[, c("Milk_z", "Frozen_z", "Delicassen_z")],
                            by = list(mydata$ClassificationWARD),
                            FUN = mean)
round(Initialleaders, 3)
##   Group.1 Milk_z Frozen_z Delicassen_z
## 1       1 -0.114   -0.403       -0.231
## 2       2  2.069    0.211        2.359
## 3       3 -0.334    1.736        0.073
Initial leaders for Group 1: Milk (-0.11), Frozen (-0.40) and Delicassen (-0.23).
#Performing K-Means clustering - initial leaders are chosen as centroids of groups, found with hierarchical clustering
library(factoextra)
K_MEANS <- hkmeans(mydata[, c("Milk_z", "Frozen_z", "Delicassen_z")],
                   k = 3,
                   hc.metric = "euclidian",
                   hc.method = "ward.D2")

K_MEANS
## Hierarchical K-means clustering with 3 clusters of sizes 346, 26, 61
## 
## Cluster means:
##       Milk_z   Frozen_z Delicassen_z
## 1 -0.1382723 -0.3684683  -0.18906729
## 2  2.4919306  0.2950475   2.36546155
## 3 -0.2778354  1.9642426   0.06418494
## 
## Clustering vector:
##   [1] 1 1 2 3 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 2 1 1 1 2 1 1 1 1 3 1 1 1 1
##  [38] 1 3 3 1 1 1 1 2 1 1 2 1 1 1 1 1 1 2 1 1 1 1 2 1 1 1 2 1 1 3 1 3 2 3 3 1 1
##  [75] 3 1 1 1 1 1 1 1 1 2 3 1 1 3 2 1 1 1 1 1 3 1 1 1 3 1 1 1 1 1 1 1 1 3 1 1 1
## [112] 1 1 1 1 1 1 1 1 1 3 3 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 3 1 2 1 1 1 1 1 1 1
## [149] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 3 1 1 1 1 2 1 1 1 1 3 1 1 3
## [186] 1 1 1 1 3 3 1 1 1 1 1 2 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 2 1 1 1 3 3 1 1 1 1
## [223] 1 3 3 1 1 1 1 1 1 1 1 3 3 1 1 1 1 1 1 1 1 3 1 2 3 1 2 1 1 1 3 1 1 3 1 1 1
## [260] 2 1 1 1 1 1 1 1 1 1 1 1 3 3 1 1 1 3 3 3 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [297] 1 1 1 1 1 1 1 2 3 1 1 1 1 2 1 1 1 2 1 1 1 1 1 1 1 3 1 1 1 1 1 3 1 1 3 3 3
## [334] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 3
## [371] 1 1 1 1 3 1 1 2 1 1 1 1 1 3 1 1 3 1 1 1 3 1 1 1 3 1 1 1 1 3 1 1 1 1 1 1 3
## [408] 3 1 1 1 1 1 1 1 1 1 1 3 1 3 1 1 1 3 1 1 1 3 1 1 1 1
## 
## Within cluster sum of squares by cluster:
## [1] 340.6654 222.6405 117.2247
##  (between_SS / total_SS =  47.5 %)
## 
## Available components:
## 
##  [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
##  [6] "betweenss"    "size"         "iter"         "ifault"       "data"        
## [11] "hclust"

Final leaders are different from inital leaders. For group 1 final leaders are Milk (-0.14), Frozen (-0.37) and Delicassen (-0.19).

346 units are in group 1, 26 in group 2 and 61 in group 3.

mydata$ClassificationK_MEANS <- K_MEANS$cluster
head(mydata[, c("ID", "ClassificationWARD", "ClassificationK_MEANS")], 15)
##    ID ClassificationWARD ClassificationK_MEANS
## 1   1                  1                     1
## 2   2                  1                     1
## 3   3                  2                     2
## 4   4                  3                     3
## 5   5                  2                     2
## 6   6                  1                     1
## 7   7                  1                     1
## 8   8                  1                     1
## 9   9                  1                     1
## 10 10                  1                     1
## 11 11                  3                     1
## 12 12                  1                     1
## 13 13                  1                     1
## 14 14                  1                     1
## 15 15                  1                     1

After K means clustering, ID stays in group 1. ID 11 was reclassified from group 3 to 1.

table(mydata$ClassificationWARD) #initial clustering
## 
##   1   2   3 
## 330  30  73

After hierarchical clustering group 1 have 330 units, group 2 has 30 units and group 3 has 73 units.

table(mydata$ClassificationK_MEANS) #K-Means clustering
## 
##   1   2   3 
## 346  26  61

After K-MEANS clustering group 1 has 346 units, group 2 has 26 units and group 3 has 61 units.

table(mydata$ClassificationWARD, mydata$ClassificationK_MEANS)
##    
##       1   2   3
##   1 328   1   1
##   2   5  25   0
##   3  13   0  60

Initially after hierarchical clustering there was 330 units in group 1. 328 units stayed in group 1, 1 was reclassified to group 2 and 1 unit was reclassified to group 3.

After K-MEANS clustering we have 346 units in group 1. 328 stayed in group in 1, 5 units came from group 2 and 13 from group 3.

Averages <- K_MEANS$centers #Final leaders
round(Averages, 3)
##   Milk_z Frozen_z Delicassen_z
## 1 -0.138   -0.368       -0.189
## 2  2.492    0.295        2.365
## 3 -0.278    1.964        0.064
library(ggplot2)
library(tidyr)
Picture <- as.data.frame(Averages)
Picture$id <- 1:nrow(Picture)
Picture <- pivot_longer (Picture, cols = c("Milk_z", "Frozen_z", "Delicassen_z"))

Picture$Group <- factor(Picture$id,
                        levels = c(1, 2, 3),
                        labels = c("1","2","3"))
Picture$nameFactor <- factor(Picture$name,
                        levels = c("Milk_z", "Frozen_z", "Delicassen_z"),
                        labels = c("Milk","Frozen","Delicassen"))

ggplot(Picture, aes(x = nameFactor, y = value)) +
  geom_hline(yintercept = 0) +
  theme_bw() +
  geom_point(aes(shape = Group, col = Group), size = 3) +
  geom_line(aes(group = id, linetype = Group, col = Group), linewidth = 0.5) +
  ylab ("Average") +
  xlab ("Cluster variables")

#### G1: Below average group. #### G2: little above average group for frozen, a lot above average for milk and delicassen. #### G3: below average group for milk, above average for frozen and average for delicassen.

#Are all of the cluster variables successful at classifying units into groups?
fit <- aov(cbind(Milk_z, Frozen_z, Delicassen_z) ~ as.factor(ClassificationK_MEANS),
           data = mydata)
summary(fit)
##  Response 1 :
##                                   Df Sum Sq Mean Sq F value    Pr(>F)    
## as.factor(ClassificationK_MEANS)   2 172.78  86.388   143.3 < 2.2e-16 ***
## Residuals                        430 259.22   0.603                      
## ---
## 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(ClassificationK_MEANS)   2 284.59 142.296  415.09 < 2.2e-16 ***
## Residuals                        430 147.41   0.343                      
## ---
## 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(ClassificationK_MEANS)   2  158.1  79.050   124.1 < 2.2e-16 ***
## Residuals                        430  273.9   0.637                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

H0: mean milk G1 = mean milk G2 = mean milk G3

H1: at least one mean is different.

Based on the ANOVA, we can reject H0 for each cluster variable and conclude that all are acceptable (p<0.001)

#Pearson chi2 test
chi_square <- chisq.test(mydata$RegionF, as.factor(mydata$ClassificationK_MEANS))
## Warning in chisq.test(mydata$RegionF, as.factor(mydata$ClassificationK_MEANS)):
## Chi-squared approximation may be incorrect
chi_square
## 
##  Pearson's Chi-squared test
## 
## data:  mydata$RegionF and as.factor(mydata$ClassificationK_MEANS)
## X-squared = 0.65674, df = 4, p-value = 0.9566

no statistically significant differences in the region structure of the groups. (p=0.96)

Warning appears if one of the expected frequencies is below 5, we have to check expected frequencies.

round(chi_square$expected, 2)
##               
## mydata$RegionF      1     2     3
##         Lisnon  61.53  4.62 10.85
##         Oporto  36.76  2.76  6.48
##         Other  247.71 18.61 43.67

Since 2 of them are below 5, which is almost 20% which is the treshold, we can still continue with the analysis.

round(chi_square$res, 2)
##               
## mydata$RegionF     1     2     3
##         Lisnon -0.19  0.64  0.05
##         Oporto  0.04  0.14 -0.19
##         Other   0.08 -0.37  0.05

In group 1, more than expected from other regions and Oporto, less than expected from Lisnon.

chi_square <- chisq.test(mydata$ChannelF, as.factor(mydata$ClassificationK_MEANS))
chi_square
## 
##  Pearson's Chi-squared test
## 
## data:  mydata$ChannelF and as.factor(mydata$ClassificationK_MEANS)
## X-squared = 32.756, df = 2, p-value = 7.711e-08

H0: there is no association between channel and classification.

H1: there is association between channel and classification.

BSD, we can reject HO and conclude that there is association between channel and classification. (p<0.001)

round(chi_square$expected, 2)
##                
## mydata$ChannelF      1     2     3
##          horeca 235.73 17.71 41.56
##          retail 110.27  8.29 19.44

All expected frequencies are above 5. Condition is met.

round(chi_square$res, 2)
##                
## mydata$ChannelF     1     2     3
##          horeca -0.31 -2.31  2.24
##          retail  0.45  3.37 -3.28

In group 2, less than expected hotel, restaurants,cafes (alfa = 0.05) and more than expected retail (alfa= 0.001).

Conclusion:

Group 1 contains the most clients of a wholesale distributor (57%, 246/433), charactarized by a below average value of all cluster variables. The clients spent the least monetary units on frozen, milk and delicatessen. There are more than expected clients from other regions and Oporto in this group and less than expected from Lisnon. There is less than expected clients from hotel, restaurants, cafes and more than expected from retail.