#install.packages("readxl")
library(readxl)
mydata <- read_xlsx("~/IMB/MVA/Homework 4/Data 4.xlsx")

mydata <- as.data.frame(mydata)
head(mydata)
##      ID Age Income Children Cars PurchasedBike Gender MaritalStatus
## 1 12496  42  40000        1    0            No Female       Married
## 2 24107  43  30000        3    1            No   Male       Married
## 3 14177  60  80000        5    2            No   Male       Married
## 4 24381  41  70000        0    1           Yes   Male        Single
## 5 25597  36  30000        0    0           Yes   Male        Single
## 6 13507  50  10000        2    0            No Female       Married
##    Region
## 1  Europe
## 2  Europe
## 3  Europe
## 4 Pacific
## 5  Europe
## 6  Europe

Description:

Source of data: Kaggle’s dataset on Bike Buyers

set.seed(1) 
mydata <- mydata[sample(nrow(mydata), 300), ]
#Standardizing variables
mydata$Age_z <- scale(mydata$Age)

mydata$Income_z   <- scale(mydata$Income)

mydata$Children_z <- scale(mydata$Children)

mydata$Cars_z <- scale(mydata$Cars)
#Checking for NA in the data
any(is.na(mydata))
## [1] FALSE
#Making factors
mydata$PurchasedBikeF <- factor(mydata$PurchasedBike, 
                                levels = c("Yes", "No"), 
                                labels = c("Yes", "No"))

mydata$GenderF <- factor(mydata$Gender, 
                                levels = c("Female", "Male"), 
                                labels = c("Female", "Male"))

mydata$MaritalStatusF <- factor(mydata$MaritalStatus, 
                                levels = c("Married", "Single"), 
                                labels = c("Married", "Single"))

mydata$RegionF <- factor(mydata$Region, 
                                levels = c("Europe", "Pacific", "North America"), 
                                labels = c("Europe", "Pacific", "North America"))

#Showing mydata   
head(mydata, 5)
##        ID Age Income Children Cars PurchasedBike Gender MaritalStatus
## 836 12922  40  60000        3    0           Yes Female        Single
## 679 18145  62  80000        5    2            No   Male       Married
## 129 20970  52  10000        2    1           Yes   Male        Single
## 930 23459  50  60000        2    2            No   Male       Married
## 509 16337  29  60000        0    2            No   Male       Married
##            Region      Age_z   Income_z  Children_z     Cars_z
## 836 North America -0.3850299  0.1126861  0.69050676 -1.2481598
## 679        Europe  1.6033874  0.7691098  1.94978960  0.4500168
## 129        Europe  0.6995614 -1.5283733  0.06086534 -0.3990715
## 930 North America  0.5187961  0.1126861  0.06086534  0.4500168
## 509 North America -1.3792385  0.1126861 -1.19841750  0.4500168
##     PurchasedBikeF GenderF MaritalStatusF       RegionF
## 836            Yes  Female         Single North America
## 679             No    Male        Married        Europe
## 129            Yes    Male         Single        Europe
## 930             No    Male        Married North America
## 509             No    Male        Married North America
#install.packages("psych")
library (psych)

subset_df <- mydata[c("Age", "Income", "Children", "Cars")]

mydata2 <- describe(subset_df)

print(mydata2)
##          vars   n     mean       sd  median  trimmed      mad   min
## Age         1 300    44.26    11.06    43.0    43.55    11.12    25
## Income      2 300 56566.67 30468.12 60000.0 54541.67 29652.00 10000
## Children    3 300     1.90     1.59     2.0     1.78     1.48     0
## Cars        4 300     1.47     1.18     1.5     1.37     0.74     0
##             max  range skew kurtosis      se
## Age          80     55 0.53    -0.21    0.64
## Income   130000 120000 0.50    -0.24 1759.08
## Children      5      5 0.43    -0.92    0.09
## Cars          4      4 0.44    -0.50    0.07
#Checking correlation among cluster variables
library(Hmisc)
## 
## Attaching package: 'Hmisc'
## The following object is masked from 'package:psych':
## 
##     describe
## The following objects are masked from 'package:base':
## 
##     format.pval, units
rcorr(as.matrix(mydata[, c("Age_z", "Income_z", "Children_z", "Cars_z")]), 
      type = "pearson")
##            Age_z Income_z Children_z Cars_z
## Age_z       1.00     0.19       0.52   0.20
## Income_z    0.19     1.00       0.29   0.45
## Children_z  0.52     0.29       1.00   0.26
## Cars_z      0.20     0.45       0.26   1.00
## 
## n= 300 
## 
## 
## P
##            Age_z  Income_z Children_z Cars_z
## Age_z             0.0012   0.0000     0.0006
## Income_z   0.0012          0.0000     0.0000
## Children_z 0.0000 0.0000              0.0000
## Cars_z     0.0006 0.0000   0.0000
#Finding outliers (Euclidian distances)
mydata$Dissimilarity <- sqrt(mydata$Age_z^2 + mydata$Income_z^2 + mydata$Children_z^2 + mydata$Cars_z^2)
# Showing 10 units with the highest value of dissimilarity
head(mydata[order(-mydata$Dissimilarity), ], 10)
##        ID Age Income Children Cars PurchasedBike Gender MaritalStatus
## 851 12205  67 130000        2    4            No Female        Single
## 402 11555  80  40000        1    0            No Female       Married
## 749 15412  69 130000        2    3            No   Male       Married
## 73  24857  52 130000        3    4            No Female       Married
## 334 18160  51 130000        3    4           Yes   Male       Married
## 504 20339  44 130000        1    4           Yes Female       Married
## 987 23704  60  40000        5    4           Yes   Male        Single
## 252 18172  55 130000        4    3            No   Male       Married
## 339 15926  50 120000        3    4           Yes Female        Single
## 457 26385  50 120000        3    4            No   Male        Single
##            Region       Age_z   Income_z  Children_z    Cars_z
## 851 North America  2.05530040  2.4101692  0.06086534  2.148193
## 402        Europe  3.23027425 -0.5437377 -0.56877608 -1.248160
## 749 North America  2.23606561  2.4101692  0.06086534  1.299105
## 73         Europe  0.69956135  2.4101692  0.69050676  2.148193
## 334        Europe  0.60917875  2.4101692  0.69050676  2.148193
## 504 North America -0.02349948  2.4101692 -0.56877608  2.148193
## 987 North America  1.42262218 -0.5437377  1.94978960  2.148193
## 252        Europe  0.97070916  2.4101692  1.32014818  1.299105
## 339        Europe  0.51879614  2.0819573  0.69050676  2.148193
## 457        Europe  0.51879614  2.0819573  0.69050676  2.148193
##     PurchasedBikeF GenderF MaritalStatusF       RegionF Dissimilarity
## 851             No  Female         Single North America      3.827743
## 402             No  Female        Married        Europe      3.551300
## 749             No    Male        Married North America      3.535574
## 73              No  Female        Married        Europe      3.374883
## 334            Yes    Male        Married        Europe      3.357313
## 504            Yes  Female        Married North America      3.278370
## 987            Yes    Male         Single North America      3.276571
## 252             No    Male        Married        Europe      3.190871
## 339            Yes  Female         Single        Europe      3.113716
## 457             No    Male         Single        Europe      3.113716
#Showing dissimilarity matrix
#install.packages("factoextra")
library(factoextra)
## Loading required package: ggplot2
## 
## Attaching package: 'ggplot2'
## The following objects are masked from 'package:psych':
## 
##     %+%, alpha
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
#Calculating Euclidean distances
distance <- get_dist(mydata[c("Age_z", "Income_z", "Children_z", "Cars_z")], 
                     method = "euclidian")

distance2 <- distance^2

fviz_dist(distance2) 

#Hopkins statistics
get_clust_tendency(mydata[c("Age_z", "Income_z", "Children_z", "Cars_z")], 
                   n = nrow(mydata) - 1, 
                   graph = FALSE)
## $hopkins_stat
## [1] 0.7511495
## 
## $plot
## NULL
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
WARD <- mydata[c("Age_z", "Income_z", "Children_z", "Cars_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: 300
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)

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

set.seed(1)
#install.packages("NbClust")
library(NbClust)
OptNumber <- mydata[c("Age_z", "Income_z", "Children_z", "Cars_z")] %>%
  #scale() %>%
  NbClust(distance = "euclidean",
          min.nc = 2, max.nc = 10, 
          method = "ward.D2", 
          index = "all")

## *** : The Hubert index is a graphical method of determining the number of clusters.
##                 In the plot of Hubert index, we seek a significant knee that corresponds to a 
##                 significant increase of the value of the measure i.e the significant peak in Hubert
##                 index second differences plot. 
## 

## *** : The D index is a graphical method of determining the number of clusters. 
##                 In the plot of D index, we seek a significant knee (the significant peak in Dindex
##                 second differences plot) that corresponds to a significant increase of the value of
##                 the measure. 
##  
## ******************************************************************* 
## * Among all indices:                                                
## * 6 proposed 2 as the best number of clusters 
## * 7 proposed 3 as the best number of clusters 
## * 1 proposed 4 as the best number of clusters 
## * 1 proposed 5 as the best number of clusters 
## * 1 proposed 7 as the best number of clusters 
## * 2 proposed 8 as the best number of clusters 
## * 1 proposed 9 as the best number of clusters 
## * 4 proposed 10 as the best number of clusters 
## 
##                    ***** Conclusion *****                            
##  
## * According to the majority rule, the best number of clusters is  3 
##  
##  
## *******************************************************************
#Cutting the dendrogram
mydata$ClusterWard <- cutree(WARD, 
                             k = 3)
head(mydata[, c("ID", "ClusterWard")])
##        ID ClusterWard
## 836 12922           1
## 679 18145           1
## 129 20970           2
## 930 23459           1
## 509 16337           2
## 471 15612           2
#Calculating positions of initial leaders

Initial_leaders <- aggregate(mydata[, c("Age_z", "Income_z", "Children_z", "Cars_z")], 
                             by = list(mydata$ClusterWard), 
                             FUN = mean)

Initial_leaders
##   Group.1      Age_z    Income_z Children_z     Cars_z
## 1       1  0.5777959  0.07165959  0.6424091  0.1139193
## 2       2 -0.7473198 -0.63475441 -0.7433825 -0.6059922
## 3       3  0.1548230  1.76261603 -0.1093080  1.5056401
library(factoextra)

#Performing K-Means clustering - initial leaders are chosen as centroids of groups, found with hierarhical clustering

K_MEANS <- hkmeans(mydata[c("Age_z", "Income_z", "Children_z", "Cars_z")], 
                   k = 3,
                   hc.metric = "euclidean",
                   hc.method = "ward.D2")

K_MEANS
## Hierarchical K-means clustering with 3 clusters of sizes 117, 146, 37
## 
## Cluster means:
##        Age_z    Income_z Children_z     Cars_z
## 1  0.7822189  0.04816579  0.8250455  0.1161872
## 2 -0.6555586 -0.46955279 -0.7024671 -0.5212007
## 3  0.1132958  1.70052189  0.1629694  1.6892268
## 
## Clustering vector:
## 836 679 129 930 509 471 299 270 978 187 307 597 277 874 950 494 330 
##   2   1   1   1   2   2   1   2   1   1   2   1   2   1   1   1   1 
## 775 841 591 725  37 105 729 878 485 677 802 987 382 601 940 801 852 
##   2   1   2   1   2   1   2   1   2   2   1   1   1   1   1   1   2 
## 931 326 984 554 422 111 404 924 532 506 556 889 343 582 121  40 684 
##   1   2   3   1   2   2   2   1   2   3   2   1   2   2   1   1   3 
## 537 375 248 198 378  39 435 810 390 280 672 526 642  45 402  22 718 
##   1   3   3   1   3   2   1   1   2   2   2   1   1   2   1   3   1 
## 742 193 371 499 104 965 767 492 838 616 615 843 465 525 808 977 176 
##   2   1   1   2   2   1   1   1   2   1   3   2   1   1   2   1   1 
## 345 791 110  84 871  29 141 252 733 620 304 545 557 661 287 614 145 
##   2   1   2   2   2   1   2   3   2   2   2   3   1   2   3   3   2 
## 329 487 855 851 630 498 858 816 619 576 490 736 103 316  51 907 290 
##   2   3   2   3   2   2   2   2   1   1   2   2   2   2   2   2   1 
## 650 998 811 282 143 442 285 682  48 501 716 511 295 536 693 214 918 
##   2   2   1   2   2   1   2   1   1   1   2   2   2   1   2   3   3 
## 737 339 346 675  43   1 910 590 959 796 628 233 293 573 369 451  86 
##   2   3   2   1   2   2   2   1   1   1   1   1   2   2   1   2   2 
## 483 327 622 355 819 812  49 361 885 242 440 758 817 818 247 751 219 
##   2   2   1   2   2   2   2   2   1   2   1   2   1   1   3   1   2 
## 135 961 958 377 408 884 565 467 356 130 891  65 842 359 992 124  77 
##   2   3   2   1   2   2   2   1   3   2   1   2   3   1   2   3   2 
## 218 610 194  19 273 418 543 419 686 403 749 587  16 951 777 604 634 
##   2   2   3   2   1   1   2   2   1   2   3   1   2   2   1   2   3 
## 664 138 719 500 761 939 229 423 421 140 126 938 508 854 968 271 821 
##   1   2   1   2   1   2   2   3   3   1   3   1   2   2   1   2   3 
## 577 512 849 504 457 358 724 127 645  41 548 305 413 955 880 309 773 
##   2   1   3   3   3   2   1   2   1   2   1   1   2   2   1   2   1 
## 441 117 764 470 900 562 336 349  72 857 474 168 872 788 455 783 822 
##   3   2   2   1   1   1   1   2   2   2   2   3   1   1   2   1   2 
## 625 234 484 952  73 539 553  15 762 294  62 941 644  35 381 814 820 
##   2   2   1   2   3   1   1   2   1   2   2   2   2   1   2   1   2 
## 697 846 665  31 549  28 735 148 772 572 284 334 980 268  93 756 300 
##   2   1   2   1   1   2   3   2   2   1   1   3   2   1   2   1   1 
## 834 976 241  33 883 437 792 848 217 108 781 
##   2   2   2   2   2   1   2   2   1   1   1 
## 
## Within cluster sum of squares by cluster:
## [1] 277.9541 248.1887  96.1030
##  (between_SS / total_SS =  48.0 %)
## 
## Available components:
## 
##  [1] "cluster"      "centers"      "totss"        "withinss"    
##  [5] "tot.withinss" "betweenss"    "size"         "iter"        
##  [9] "ifault"       "data"         "hclust"
mydata$ClassificationK_MEANS <- K_MEANS$cluster
head(mydata[, c("ID", "ClusterWard", "ClassificationK_MEANS")])
##        ID ClusterWard ClassificationK_MEANS
## 836 12922           1                     2
## 679 18145           1                     1
## 129 20970           2                     1
## 930 23459           1                     1
## 509 16337           2                     2
## 471 15612           2                     2
#Checking for reclassifications
table(mydata$ClusterWard)
## 
##   1   2   3 
## 144 119  37
table(mydata$ClassificationK_MEANS)
## 
##   1   2   3 
## 117 146  37
# To see where from/where to units have reclassified
table(mydata$ClusterWard, mydata$ClassificationK_MEANS)
##    
##       1   2   3
##   1 110  30   4
##   2   6 113   0
##   3   1   3  33
Averages <- K_MEANS$centers
round(Averages, 3)
##    Age_z Income_z Children_z Cars_z
## 1  0.782    0.048      0.825  0.116
## 2 -0.656   -0.470     -0.702 -0.521
## 3  0.113    1.701      0.163  1.689
library(ggplot2)
library(tidyr)
Picture <- as.data.frame(Averages)
Picture$id <- 1:nrow(Picture)
Picture <- pivot_longer(Picture, cols = c("Age_z", "Income_z", "Children_z", "Cars_z"))

Picture$Group <- factor(Picture$id, 
                        levels = c(1, 2, 3), 
                        labels = c("1", "2", "3"))

Picture$nameFactor <- factor(Picture$name, 
                             levels = c("Age_z", "Income_z", "Children_z", "Cars_z"), 
                             labels = c("Age", "Income", "Children", "Cars"))

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 = 1) +
  ylab("Average") +
  xlab("Cluster variables")

# Checking the appropriateness of the cluster variables used
fit <- aov(cbind(Age_z, Income_z, Children_z, Cars_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 134.81  67.404  121.92 < 2.2e-16
## Residuals                        297 164.19   0.553                  
##                                     
## as.factor(ClassificationK_MEANS) ***
## Residuals                           
## ---
## 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 139.46  69.729   129.8 < 2.2e-16
## Residuals                        297 159.54   0.537                  
##                                     
## as.factor(ClassificationK_MEANS) ***
## Residuals                           
## ---
## 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 152.67  76.335  154.93 < 2.2e-16
## Residuals                        297 146.33   0.493                  
##                                     
## as.factor(ClassificationK_MEANS) ***
## Residuals                           
## ---
## 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(ClassificationK_MEANS)   2 146.82  73.410  143.27 < 2.2e-16
## Residuals                        297 152.18   0.512                  
##                                     
## as.factor(ClassificationK_MEANS) ***
## Residuals                           
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#Pearson Chi2 test, for checking the validity of the classification
# No need to use Yates corrections, because we do not have 2x2 table

chisq_results <- chisq.test(mydata$GenderF, as.factor(mydata$ClassificationK_MEANS))
chisq_results
## 
##  Pearson's Chi-squared test
## 
## data:  mydata$GenderF and as.factor(mydata$ClassificationK_MEANS)
## X-squared = 0.11038, df = 2, p-value = 0.9463
addmargins(chisq_results$observed)
##               
## mydata$GenderF   1   2   3 Sum
##         Female  56  67  17 140
##         Male    61  79  20 160
##         Sum    117 146  37 300
round(chisq_results$expected, 2)
##               
## mydata$GenderF    1     2     3
##         Female 54.6 68.13 17.27
##         Male   62.4 77.87 19.73
round(chisq_results$res, 2)
##               
## mydata$GenderF     1     2     3
##         Female  0.19 -0.14 -0.06
##         Male   -0.18  0.13  0.06
chisq_results <- chisq.test(mydata$PurchasedBikeF, as.factor(mydata$ClassificationK_MEANS))
chisq_results
## 
##  Pearson's Chi-squared test
## 
## data:  mydata$PurchasedBikeF and as.factor(mydata$ClassificationK_MEANS)
## X-squared = 4.2438, df = 2, p-value = 0.1198
addmargins(chisq_results$observed)
##                      
## mydata$PurchasedBikeF   1   2   3 Sum
##                   Yes  47  75  14 136
##                   No   70  71  23 164
##                   Sum 117 146  37 300
round(chisq_results$expected, 2)
##                      
## mydata$PurchasedBikeF     1     2     3
##                   Yes 53.04 66.19 16.77
##                   No  63.96 79.81 20.23
round(chisq_results$res, 2)
##                      
## mydata$PurchasedBikeF     1     2     3
##                   Yes -0.83  1.08 -0.68
##                   No   0.76 -0.99  0.62
chisq_results <- chisq.test(mydata$MaritalStatusF, as.factor(mydata$ClassificationK_MEANS))
chisq_results
## 
##  Pearson's Chi-squared test
## 
## data:  mydata$MaritalStatusF and as.factor(mydata$ClassificationK_MEANS)
## X-squared = 5.1941, df = 2, p-value = 0.07449
addmargins(chisq_results$observed)
##                      
## mydata$MaritalStatusF   1   2   3 Sum
##               Married  72  70  18 160
##               Single   45  76  19 140
##               Sum     117 146  37 300
round(chisq_results$expected, 2)
##                      
## mydata$MaritalStatusF    1     2     3
##               Married 62.4 77.87 19.73
##               Single  54.6 68.13 17.27
round(chisq_results$res, 2)
##                      
## mydata$MaritalStatusF     1     2     3
##               Married  1.22 -0.89 -0.39
##               Single  -1.30  0.95  0.42
chisq_results <- chisq.test(mydata$RegionF, as.factor(mydata$ClassificationK_MEANS))
chisq_results
## 
##  Pearson's Chi-squared test
## 
## data:  mydata$RegionF and as.factor(mydata$ClassificationK_MEANS)
## X-squared = 33.629, df = 4, p-value = 8.877e-07
addmargins(chisq_results$observed)
##                
## mydata$RegionF    1   2   3 Sum
##   Europe         17  64  10  91
##   Pacific        24  13  11  48
##   North America  76  69  16 161
##   Sum           117 146  37 300
round(chisq_results$expected, 2)
##                
## mydata$RegionF      1     2     3
##   Europe        35.49 44.29 11.22
##   Pacific       18.72 23.36  5.92
##   North America 62.79 78.35 19.86
round(chisq_results$res, 2)
##                
## mydata$RegionF      1     2     3
##   Europe        -3.10  2.96 -0.37
##   Pacific        1.22 -2.14  2.09
##   North America  1.67 -1.06 -0.87