Homework 4: Clustering Rok Rojc

Source: https://www.kaggle.com/datasets/mirichoi0218/insurance?resource=download

library(readxl)
mydata <- read_xlsx("~/Desktop/MCP.xlsx")

set.seed(1)
mydata <- mydata[sample(nrow(mydata), 500), ] #Random sample of 500 units
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
colnames(mydata) <-c("ID", "Age","Gender","BMI","Children","Smoker","Region","MedicalCost")
mydata$BMI <- as.numeric(mydata$BMI)
mydata$MedicalCost <- as.numeric(mydata$MedicalCost) #changing data to numeric
mydata$GenderF <- factor(mydata$Gender,
                          labels = c("Male", "Female"),
                          levels = c("male", "female")) 
mydata$Smoker <- factor(mydata$Smoker,
                             labels = c("Smoker", "Non-smoker"),
                             levels = c("yes", "no"))
mydata$Region <- factor(mydata$Region,
                             labels = c("Northeast", "Southeast", "Southwest", "Northwest"),
                             levels = c("northeast", "southeast", "southwest", "northwest")) #changing variables into factors
head(mydata)
## # A tibble: 6 × 9
##      ID   Age Gender     BMI Children Smoker     Region    MedicalCost GenderF
##   <dbl> <dbl> <chr>    <dbl>    <dbl> <fct>      <fct>           <dbl> <fct>  
## 1  1017    19 female 24605          1 Non-smoker Northwest       2709. Female 
## 2   679    56 male      36.1        3 Non-smoker Southwest      12364. Male   
## 3   129    32 female 17765          2 Smoker     Northwest      32734. Female 
## 4   930    41 male      34.2        1 Non-smoker Southeast       6290. Male   
## 5   471    27 male      32.7        0 Non-smoker Southeast       2497. Male   
## 6   299    31 male      34.4        3 Smoker     Northwest      38746. Male

Description of variables:

The research question for this analysis is: Find out how we can separate the observations into different clusters based on the variables age, bmi, children and charges. (classification of 500 primary beneficiaries (people) of health insurance based on Age, BMI, number of children and medical charges)

summary(mydata[c("Age", "Children", "BMI", "MedicalCost")])
##       Age           Children          BMI            MedicalCost   
##  Min.   :18.00   Min.   :0.000   Min.   :   15.96   Min.   : 1136  
##  1st Qu.:26.00   1st Qu.:0.000   1st Qu.:   28.31   1st Qu.: 4687  
##  Median :39.00   Median :1.000   Median :   33.84   Median : 9285  
##  Mean   :38.97   Mean   :1.064   Mean   : 7447.44   Mean   :13104  
##  3rd Qu.:51.00   3rd Qu.:2.000   3rd Qu.:18050.00   3rd Qu.:16121  
##  Max.   :64.00   Max.   :5.000   Max.   :41325.00   Max.   :62593
# Checking variance before standardizing the data => not the same
var(mydata$Age)
## [1] 199.941
var(mydata$MedicalCost)
## [1] 145387633
mydata_std <- as.data.frame(scale(mydata[c("Age", "Children", "BMI", "MedicalCost")]))
var(mydata_std$Age) #because data is scaled/standardized variance is equal to 1
## [1] 1
var(mydata_std$MedicalCost)
## [1] 1

I standardized variances so the units have the same impact.

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
# Checking the correlation of the variables, we want it to be low
rcorr(as.matrix(mydata_std[, c("Age", "Children", "BMI", "MedicalCost")]),
      type="pearson")
##              Age Children  BMI MedicalCost
## Age         1.00     0.05 0.04        0.31
## Children    0.05     1.00 0.04        0.05
## BMI         0.04     0.04 1.00        0.04
## MedicalCost 0.31     0.05 0.04        1.00
## 
## n= 500 
## 
## 
## P
##             Age    Children BMI    MedicalCost
## Age                0.2852   0.3318 0.0000     
## Children    0.2852          0.3352 0.2851     
## BMI         0.3318 0.3352          0.3451     
## MedicalCost 0.0000 0.2851   0.3451

Correlations are low, which is a good indicator.

mydata_std$Dissimilarity <- sqrt(mydata_std$Age^2 + mydata_std$BMI^2 + mydata_std$Children^2 + mydata_std$MedicalCost^2)
head(mydata_std[order(-mydata_std$Dissimilarity), ], 7) # Calculating the dissimilarity
##            Age   Children        BMI MedicalCost Dissimilarity
## 135  0.9214961  1.6560701  2.0895530   3.8910848      4.806089
## 82   1.0629383  1.6560701  2.5594358   2.9396397      4.366303
## 10   0.4264483 -0.9101542 -0.5732171   4.1043492      4.264329
## 423  1.6287072  1.6560701  1.8105601   2.7877850      4.055259
## 260  1.3458228  0.8006620  2.2804429   2.8523356      3.973479
## 308  0.6386117  0.8006620  2.5594358   2.7035116      3.861162
## 212 -1.4123006  3.3668864 -0.5733531  -0.6979907      3.761176
print(mydata[c(135, 82, 10), ])
## # A tibble: 3 × 9
##      ID   Age Gender     BMI Children Smoker Region    MedicalCost GenderF
##   <dbl> <dbl> <chr>    <dbl>    <dbl> <fct>  <fct>           <dbl> <fct>  
## 1  1231    52 male   34485          3 Smoker Northwest      60021. Male   
## 2   282    54 male   40565          3 Smoker Northeast      48549. Male   
## 3  1301    45 male      30.4        0 Smoker Southeast      62593. Male

Unit ID1231 has all variables quite high (it has the highest dissimilarity compared to others), unit ID282 has BMI- body mass index very high compared to other and unit ID1301 has very high medical costs compared to the others, which is why they have the highest dissimilarity score.

# Removing units with high dissimilarity and rescaling the data
mydata <- mydata %>% 
  filter(!mydata$ID %in% c(1231,282,1301))
mydata_std <- as.data.frame(scale(mydata[c("Age", "Children", "BMI", "MedicalCost")]))
#install.packages("factoextra")
library(factoextra) 
## Loading required package: ggplot2
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
Distances <- get_dist(mydata_std, 
                    method = "euclidian") #Finding Eucdlidean distances
Distances2 <- Distances^2
fviz_dist(Distances2) #Displaying matrix of distances

library(factoextra) 
get_clust_tendency(mydata_std, #Hopkins statistics
                   n = nrow(mydata_std) - 1,
                   graph = FALSE) 
## $hopkins_stat
## [1] 0.8578026
## 
## $plot
## NULL

H0: There are no natural groups of objects.

H1: There are natural groups of objects.

library(dplyr)
WARD <- mydata_std %>% 
  get_dist(method = "euclidean") %>%  
  hclust(method = "ward.D2")      
WARD
## 
## Call:
## hclust(d = ., method = "ward.D2")
## 
## Cluster method   : ward.D2 
## Distance         : euclidean 
## Number of objects: 497
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 = 5,
          cex = 0.5, 
          palette = "jama",
          color_labels_by_k = TRUE, 
          rect = TRUE)

set.seed(1)
#install.packages("NbClust")
library(NbClust)
OptNumber <- mydata_std %>%
  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:                                                
## * 3 proposed 2 as the best number of clusters 
## * 4 proposed 3 as the best number of clusters 
## * 10 proposed 5 as the best number of clusters 
## * 1 proposed 6 as the best number of clusters 
## * 1 proposed 7 as the best number of clusters 
## * 2 proposed 8 as the best number of clusters 
## * 2 proposed 10 as the best number of clusters 
## 
##                    ***** Conclusion *****                            
##  
## * According to the majority rule, the best number of clusters is  5 
##  
##  
## *******************************************************************
mydata$ClusterWard <- cutree(WARD, 
                             k = 5) #Number of groups

head(mydata[c("ClusterWard")])
## # A tibble: 6 × 1
##   ClusterWard
##         <int>
## 1           1
## 2           2
## 3           1
## 4           3
## 5           4
## 6           5

I created 5 clusters here.

Leaders_initial <- aggregate(mydata_std, 
                             by = list(mydata$ClusterWard), 
                             FUN = mean) #Showing the positions of initial leaders - initial point for k-means clustering
Leaders_initial
##   Group.1         Age   Children         BMI MedicalCost
## 1       1 -0.01054252  0.1170194  1.63009734 -0.25067018
## 2       2 -0.03987678  1.4157621 -0.56973240 -0.19595958
## 3       3  0.96326176 -0.3933973 -0.56972299 -0.01660776
## 4       4 -0.92976037 -0.6662894 -0.56981830 -0.71602715
## 5       5 -0.03567429 -0.2424566  0.02656352  2.26783175
kmeans_clu <- hkmeans(mydata_std, 
                      k = 5,
                      hc.metric = "euclidean", #Distance
                      hc.method = "ward.D2") #Algorithm
kmeans_clu
## Hierarchical K-means clustering with 5 clusters of sizes 108, 101, 114, 120, 54
## 
## Cluster means:
##           Age   Children         BMI MedicalCost
## 1  0.03248360  0.1247555  1.67700371 -0.21627315
## 2  0.05454124  1.3520755 -0.55427259 -0.17020620
## 3  0.97640245 -0.5469860 -0.52896120 -0.02151926
## 4 -0.97347128 -0.6365794 -0.52982529 -0.69839562
## 5 -0.06500406 -0.2090239 -0.02322701  2.34831474
## 
## Clustering vector:
##   [1] 1 2 5 3 4 5 3 1 2 3 1 4 4 2 2 3 5 4 3 3 4 1 3 2 3 3 2 4 3 4 2 5 2 4 4 2 5
##  [38] 5 1 4 4 2 3 4 4 2 2 2 5 1 1 2 3 2 3 3 5 2 3 3 2 2 2 5 2 1 5 4 5 3 4 5 3 3
##  [75] 3 2 1 4 2 1 3 3 1 5 3 1 1 1 1 5 2 3 4 3 4 2 1 2 1 4 4 2 1 2 3 2 3 3 4 1 4
## [112] 1 2 3 3 5 3 2 3 4 4 4 1 3 2 2 3 4 2 1 1 1 2 1 4 2 2 3 2 4 4 1 5 5 1 4 1 3
## [149] 4 4 1 4 5 2 4 4 2 2 1 2 1 3 5 3 1 1 5 4 4 3 4 4 3 4 2 5 4 1 1 4 1 3 5 2 3
## [186] 4 2 5 2 2 4 1 4 1 3 5 1 5 3 5 2 2 1 1 5 2 4 5 2 2 4 2 3 4 4 1 2 3 3 2 2 4
## [223] 4 3 4 4 1 1 3 5 3 2 2 3 4 4 1 2 2 3 1 1 4 5 4 3 3 4 3 1 3 1 2 3 3 2 5 1 3
## [260] 4 3 4 5 2 4 3 3 2 2 4 5 3 1 3 4 1 3 1 5 3 3 4 2 1 4 2 3 4 2 1 3 4 1 2 2 2
## [297] 3 3 3 4 5 5 2 2 5 4 1 4 3 2 1 4 4 1 3 5 2 4 1 3 4 1 1 4 1 4 5 1 4 2 4 3 2
## [334] 3 3 3 2 5 4 4 1 2 5 1 3 4 2 4 1 3 4 1 4 2 1 1 4 1 4 1 4 4 1 1 1 4 4 3 1 5
## [371] 1 2 5 1 3 4 4 4 5 3 1 1 4 1 2 1 4 5 2 2 3 3 3 5 1 2 4 1 3 2 3 4 1 3 3 3 1
## [408] 1 3 1 1 3 3 3 1 3 2 1 2 5 3 4 3 1 1 4 4 4 5 1 2 4 2 1 3 1 1 2 5 5 3 3 4 2
## [445] 3 3 4 3 4 3 3 5 4 3 1 4 3 2 4 4 4 4 2 4 2 1 4 3 5 2 2 4 1 4 4 2 2 1 1 1 1
## [482] 2 5 2 3 3 4 5 4 4 3 1 1 1 1 3 4
## 
## Within cluster sum of squares by cluster:
## [1] 246.36924 142.64570  84.33488  74.19859 177.27040
##  (between_SS / total_SS =  63.5 %)
## 
## Available components:
## 
##  [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
##  [6] "betweenss"    "size"         "iter"         "ifault"       "data"        
## [11] "hclust"

The ratio between the total sum of squares and the sum of squares is 63.5%, which indicates a good fit.

print(mydata[c(305, 257, 420), ])
## # A tibble: 3 × 10
##      ID   Age Gender   BMI Children Smoker Region    MedicalCost GenderF
##   <dbl> <dbl> <chr>  <dbl>    <dbl> <fct>  <fct>           <dbl> <fct>  
## 1   570    48 male   40565        2 Smoker Northwest      45702. Male   
## 2    56    58 male   36955        2 Smoker Northwest      47496. Male   
## 3  1302    62 male   30875        3 Smoker Northwest      46718. Male   
## # ℹ 1 more variable: ClusterWard <int>
fviz_cluster(kmeans_clu,
palette = "jama",
repel = FALSE,
ggtheme = theme_classic())

print(mydata[c(305, 257, 420), ]) #outliers
## # A tibble: 3 × 10
##      ID   Age Gender   BMI Children Smoker Region    MedicalCost GenderF
##   <dbl> <dbl> <chr>  <dbl>    <dbl> <fct>  <fct>           <dbl> <fct>  
## 1   570    48 male   40565        2 Smoker Northwest      45702. Male   
## 2    56    58 male   36955        2 Smoker Northwest      47496. Male   
## 3  1302    62 male   30875        3 Smoker Northwest      46718. Male   
## # ℹ 1 more variable: ClusterWard <int>
mydata$ClusterK_Means <- kmeans_clu$cluster
head(mydata[c("ClusterWard", "ClusterK_Means")])
## # A tibble: 6 × 2
##   ClusterWard ClusterK_Means
##         <int>          <int>
## 1           1              1
## 2           2              2
## 3           1              5
## 4           3              3
## 5           4              4
## 6           5              5
table(mydata$ClusterWard)
## 
##   1   2   3   4   5 
## 113  89 120 117  58
table(mydata$ClusterK_Means)
## 
##   1   2   3   4   5 
## 108 101 114 120  54
table(mydata$ClusterWard, mydata$ClusterK_Means)
##    
##       1   2   3   4   5
##   1 105   1   3   3   1
##   2   0  88   0   1   0
##   3   0  11 107   2   0
##   4   0   0   4 113   0
##   5   3   1   0   1  53

Interpretation:

I interpreted it when I removed outliers, rescaled the data and performed the second clustering, so the interpretation is there because it is the correct model.

library(tidyr)
Leaders_final <- kmeans_clu$centers
Figure <- as.data.frame(Leaders_final)
Figure$ID <- 1:nrow(Figure)
library(tidyr)
Figure <- pivot_longer( Figure , cols = c("Age", "Children", "BMI", "MedicalCost"))

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

Figure$Name <- factor(Figure$name, 
                       levels = c("Age", "Children", "BMI", "MedicalCost"), 
                       labels = c("Age", "Children", "BMI", "MedicalCost"))
head(mydata)
## # A tibble: 6 × 11
##      ID   Age Gender     BMI Children Smoker     Region    MedicalCost GenderF
##   <dbl> <dbl> <chr>    <dbl>    <dbl> <fct>      <fct>           <dbl> <fct>  
## 1  1017    19 female 24605          1 Non-smoker Northwest       2709. Female 
## 2   679    56 male      36.1        3 Non-smoker Southwest      12364. Male   
## 3   129    32 female 17765          2 Smoker     Northwest      32734. Female 
## 4   930    41 male      34.2        1 Non-smoker Southeast       6290. Male   
## 5   471    27 male      32.7        0 Non-smoker Southeast       2497. Male   
## 6   299    31 male      34.4        3 Smoker     Northwest      38746. Male   
## # ℹ 2 more variables: ClusterWard <int>, ClusterK_Means <int>
library(ggplot2)
ggplot(Figure, aes(x = Name, y = value)) +
  geom_hline(yintercept = 0) +
  theme_bw() +
  geom_point(aes(shape = Group, col = Group), size = 4) +
  geom_line(aes(group = ID), linewidth = 1) +
  ylab("Averages") +
  xlab("Cluster variables")+
  ylim(-2.4, 2.4)

I interpreted it when I removed outliers, rescaled the data and performed the second clustering, so the interpretation is there.

#Are all the cluster variables successful at classifing units into groups? Performing ANOVAs.
fit <- aov(cbind(Age, BMI, Children, MedicalCost) ~ as.factor(ClusterK_Means), 
           data = mydata)
summary(fit)
##  Response Age :
##                            Df Sum Sq Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means)   4  44670 11167.5  100.51 < 2.2e-16 ***
## Residuals                 492  54666   111.1                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
##  Response BMI :
##                            Df     Sum Sq    Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means)   4 6.5915e+10 1.6479e+10  514.99 < 2.2e-16 ***
## Residuals                 492 1.5743e+10 3.1998e+07                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
##  Response Children :
##                            Df Sum Sq Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means)   4 368.44   92.11  148.65 < 2.2e-16 ***
## Residuals                 492 304.87    0.62                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
##  Response MedicalCost :
##                            Df     Sum Sq    Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means)   4 4.8928e+10 1.2232e+10  340.41 < 2.2e-16 ***
## Residuals                 492 1.7679e+10 3.5933e+07                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Age:
  • H0: The mean age of individuals is the same across all clusters identified by k-means clustering (μ₁ = μ₂ = μ₃ = μ₄ = μ₅).

  • H1: At least one cluster has a mean age that is different from the others (At least one μₐge is not equal to the others).

BMI:
  • H0: The mean BMI is the same across all clusters identified by k-means clustering (μ₁ = μ₂ = μ₃ = μ₄ = μ₅)

  • H1: At least one cluster has a mean BMI that is different from the others (At least one μBMI is not equal to the others).

Children:
  • H0: The mean number of children covered by insurance is the same across all clusters identified by k-means clustering (μ₁ = μ₂ = μ₃ = μ₄ = μ₅).

  • H1: At least one cluster has a mean number of children that is different from the others (At least one μChildren is not equal to the others).

Medical Cost:
  • *H0: The mean medical cost is the same across all clusters identified by k-means clustering (μ₁ = μ₂ = μ₃ = μ₄ = μ₅).**

  • **H1: At least one cluster has a mean medical cost that is different from the others (At least one μMedicalCost is not equal to the others).*

Rescaling the data after finding outliers:

mydata <- mydata %>% filter(!ID %in% c(570, 56, 1302)) #removing outliers
mydata_std2 <- as.data.frame(scale(mydata[c("Age", "Children", "BMI", "MedicalCost")])) #rescaling the data
head(mydata_std2)
##          Age   Children        BMI MedicalCost
## 1 -1.4016795 -0.0434845  1.3766432 -0.87681121
## 2  1.2179420  1.6750230 -0.5628924 -0.02384064
## 3 -0.4812720  0.8157693  0.8366750  1.77593257
## 4  0.1559333 -0.0434845 -0.5630416 -0.56046829
## 5 -0.8352749 -0.9027383 -0.5631632 -0.89555987
## 6 -0.5520725  1.6750230 -0.5630274  2.30711572
#install.packages("factoextra")
library(factoextra) 
Distances3 <- get_dist(mydata_std2, 
                    method = "euclidian") #Finding Eucdlidean distances
Distances4 <- Distances3^2
fviz_dist(Distances4) #Displaying matrix of distances

library(factoextra) 
get_clust_tendency(mydata_std2, #Hopkins statistics
                   n = nrow(mydata_std2) - 1,
                   graph = FALSE) 
## $hopkins_stat
## [1] 0.8445917
## 
## $plot
## NULL

H0: There are no natural groups of objects.

H1: There are natural groups of objects.

library(dplyr)
WARD2 <- mydata_std2 %>% 
  get_dist(method = "euclidean") %>%  
  hclust(method = "ward.D2")      
WARD2
## 
## Call:
## hclust(d = ., method = "ward.D2")
## 
## Cluster method   : ward.D2 
## Distance         : euclidean 
## Number of objects: 494
kmeans_clu2 <- hkmeans(mydata_std2, 
                      k = 5,
                      hc.metric = "euclidean", #Distance
                      hc.method = "ward.D2") #Algorithm
kmeans_clu2
## Hierarchical K-means clustering with 5 clusters of sizes 112, 98, 113, 119, 52
## 
## Cluster means:
##            Age    Children        BMI MedicalCost
## 1 -0.008425228  0.09460985  1.7243013 -0.12658737
## 2  0.077908132  1.36814670 -0.5471387 -0.20443608
## 3  0.988623265 -0.54534954 -0.5216258 -0.01468897
## 4 -0.964976758 -0.62835472 -0.5225190 -0.71278218
## 5 -0.068722425 -0.15915328 -0.3534360  2.32102797
## 
## Clustering vector:
##   [1] 1 2 5 3 4 5 3 1 2 3 1 4 4 2 2 3 5 4 3 3 4 1 3 2 3 3 2 4 3 4 2 5 2 4 4 2 5
##  [38] 5 1 4 4 5 3 4 4 2 2 2 5 1 1 2 3 2 3 3 5 2 3 3 2 2 2 5 2 1 5 4 5 3 4 5 3 3
##  [75] 3 2 1 4 2 1 3 3 1 5 3 1 1 1 1 5 2 3 4 3 4 2 1 2 1 4 4 2 1 2 3 2 3 3 4 1 4
## [112] 1 2 3 3 5 3 2 3 4 4 4 1 3 2 2 3 4 2 1 1 1 2 1 4 2 2 3 2 4 4 1 5 5 1 4 1 3
## [149] 4 4 1 4 5 2 4 4 2 2 1 2 1 3 1 3 1 1 5 4 4 3 4 4 3 4 2 5 4 1 1 4 1 3 5 2 3
## [186] 4 2 5 2 2 4 1 4 1 3 5 1 5 3 5 2 2 1 1 5 2 4 5 2 5 4 2 3 4 4 1 2 3 3 2 2 4
## [223] 4 3 4 4 1 1 3 5 3 2 2 3 4 4 1 2 2 3 1 1 4 5 4 3 3 4 3 1 3 1 2 3 3 2 1 3 4
## [260] 3 4 5 2 4 5 3 2 2 4 5 3 1 3 4 1 3 1 5 3 3 4 2 1 4 2 3 4 2 1 3 4 1 2 2 2 3
## [297] 3 3 4 5 5 2 2 4 1 4 3 2 1 4 4 1 3 5 2 4 1 3 4 1 1 4 1 4 1 1 4 5 4 3 2 3 3
## [334] 3 2 5 4 4 1 2 1 1 3 4 2 4 1 3 4 1 4 2 1 1 4 1 4 1 4 4 1 1 1 4 4 3 1 5 1 2
## [371] 5 1 3 4 4 4 1 3 1 1 4 1 2 1 4 5 2 2 3 3 3 5 1 2 4 1 3 2 3 4 1 3 3 3 1 1 3
## [408] 1 1 3 3 3 1 3 2 1 2 3 4 3 1 1 4 4 4 5 1 2 4 2 1 3 1 1 2 5 5 3 3 4 2 3 3 4
## [445] 3 4 3 3 5 4 3 1 4 3 2 5 4 4 4 2 4 2 1 4 3 5 2 2 4 1 4 4 2 2 1 1 1 1 2 5 2
## [482] 3 3 4 5 4 4 3 1 1 1 1 3 4
## 
## Within cluster sum of squares by cluster:
## [1] 279.01164 134.30829  83.94162  71.77355 135.93591
##  (between_SS / total_SS =  64.3 %)
## 
## Available components:
## 
##  [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
##  [6] "betweenss"    "size"         "iter"         "ifault"       "data"        
## [11] "hclust"

The new ratio between the total sum of squares and the sum of squares after removing outliers is 64.3% (improved from before), which indicates a good fit.

fviz_dend(WARD2)

fviz_dend(WARD2, 
          k = 5,
          cex = 0.5, 
          palette = "jama",
          color_labels_by_k = TRUE, 
          rect = TRUE)

set.seed(1)
#install.packages("NbClust")
library(NbClust)
OptNumber <- mydata_std2 %>%
  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:                                                
## * 4 proposed 2 as the best number of clusters 
## * 1 proposed 3 as the best number of clusters 
## * 2 proposed 4 as the best number of clusters 
## * 11 proposed 5 as the best number of clusters 
## * 1 proposed 6 as the best number of clusters 
## * 2 proposed 8 as the best number of clusters 
## * 3 proposed 10 as the best number of clusters 
## 
##                    ***** Conclusion *****                            
##  
## * According to the majority rule, the best number of clusters is  5 
##  
##  
## *******************************************************************

From the D Index I can see that 5 clusters is indeed the most appropriate number.

fviz_cluster(kmeans_clu2,
palette = "jama",
repel = FALSE,
ggtheme = theme_classic())

Leaders_initial2 <- aggregate(mydata_std2[ , c("Age", "Children", "BMI", "MedicalCost")], 
                             by = list(mydata$ClusterWard), 
                             FUN = mean) #Showing the positions of initial leaders - initial point for k-means clustering
Leaders_initial
##   Group.1         Age   Children         BMI MedicalCost
## 1       1 -0.01054252  0.1170194  1.63009734 -0.25067018
## 2       2 -0.03987678  1.4157621 -0.56973240 -0.19595958
## 3       3  0.96326176 -0.3933973 -0.56972299 -0.01660776
## 4       4 -0.92976037 -0.6662894 -0.56981830 -0.71602715
## 5       5 -0.03567429 -0.2424566  0.02656352  2.26783175
mydata$ClusterK_Means2 <- kmeans_clu2$cluster
head(mydata[c("ClusterWard", "ClusterK_Means2")])
## # A tibble: 6 × 2
##   ClusterWard ClusterK_Means2
##         <int>           <int>
## 1           1               1
## 2           2               2
## 3           1               5
## 4           3               3
## 5           4               4
## 6           5               5
table(mydata$ClusterWard)
## 
##   1   2   3   4   5 
## 113  89 120 117  55
table(mydata$ClusterK_Means2)
## 
##   1   2   3   4   5 
## 112  98 113 119  52
table(mydata$ClusterWard, mydata$ClusterK_Means2)
##    
##       1   2   3   4   5
##   1 105   1   3   3   1
##   2   0  86   0   1   2
##   3   0  11 106   2   1
##   4   0   0   4 113   0
##   5   7   0   0   0  48

Interpretation:

Row 1: When using hierarchical clustering, the first group initially contained 113 units (105 + 1 + 3 + 3 + 1). Using K-means, 1 unit was reclassified into group 2, and 3 unit were reclassified into group 3, and 3 in group 4 and 1 unit was reclassified in group 5 while 105 remained in group 1.

Column 1: In group 1 we have 112 units (105 + 7) after having used K-means clustering. Out of these 112, 105 were there initially, 7 were reclassified from group 3.

The interpretation is the similar for all 5 rows and columns, just different number of reclassification. I interpreted 1 column and 1 row just to explain.

library(tidyr)
Leaders_final2 <- kmeans_clu2$centers
Figure2 <- as.data.frame(Leaders_final2)
Figure2$ID <- 1:nrow(Figure2)
Leaders_final2
##            Age    Children        BMI MedicalCost
## 1 -0.008425228  0.09460985  1.7243013 -0.12658737
## 2  0.077908132  1.36814670 -0.5471387 -0.20443608
## 3  0.988623265 -0.54534954 -0.5216258 -0.01468897
## 4 -0.964976758 -0.62835472 -0.5225190 -0.71278218
## 5 -0.068722425 -0.15915328 -0.3534360  2.32102797
library(tidyr)
Figure2 <- pivot_longer( Figure2, cols = c("Age", "Children", "BMI", "MedicalCost"))

Figure2$Group <- factor(Figure2$ID, 
                       levels = c(1, 2, 3, 4, 5), 
                       labels = c("1", "2", "3","4","5"))

Figure2$Name <- factor(Figure2$name, 
                       levels = c("Age", "Children", "BMI", "MedicalCost"), 
                       labels = c("Age", "Children", "BMI", "MedicalCost"))
head(mydata)
## # A tibble: 6 × 12
##      ID   Age Gender     BMI Children Smoker     Region    MedicalCost GenderF
##   <dbl> <dbl> <chr>    <dbl>    <dbl> <fct>      <fct>           <dbl> <fct>  
## 1  1017    19 female 24605          1 Non-smoker Northwest       2709. Female 
## 2   679    56 male      36.1        3 Non-smoker Southwest      12364. Male   
## 3   129    32 female 17765          2 Smoker     Northwest      32734. Female 
## 4   930    41 male      34.2        1 Non-smoker Southeast       6290. Male   
## 5   471    27 male      32.7        0 Non-smoker Southeast       2497. Male   
## 6   299    31 male      34.4        3 Smoker     Northwest      38746. Male   
## # ℹ 3 more variables: ClusterWard <int>, ClusterK_Means <int>,
## #   ClusterK_Means2 <int>
library(ggplot2)
ggplot(Figure2, aes(x = Name, y = value)) +
  geom_hline(yintercept = 0) +
  theme_bw() +
  geom_point(aes(shape = Group, col = Group), size = 4) +
  geom_line(aes(group = ID), linewidth = 1) +
  ylab("Averages") +
  xlab("Cluster variables")+
  ylim(-2.4, 2.4)

fit2 <- aov(cbind(Age, BMI, Children, MedicalCost) ~ as.factor(ClusterK_Means2), 
           data = mydata)
summary(fit2)
##  Response Age :
##                             Df Sum Sq Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means2)   4  44308 11076.9  100.23 < 2.2e-16 ***
## Residuals                  489  54042   110.5                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
##  Response BMI :
##                             Df     Sum Sq    Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means2)   4 6.9331e+10 1.7333e+10   866.9 < 2.2e-16 ***
## Residuals                  489 9.7771e+09 1.9994e+07                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
##  Response Children :
##                             Df Sum Sq Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means2)   4 360.75  90.188  143.66 < 2.2e-16 ***
## Residuals                  489 306.98   0.628                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
##  Response MedicalCost :
##                             Df     Sum Sq    Mean Sq F value    Pr(>F)    
## as.factor(ClusterK_Means2)   4 4.4390e+10 1.1098e+10  289.16 < 2.2e-16 ***
## Residuals                  489 1.8767e+10 3.8378e+07                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Age:
  • H0: The mean age of individuals is the same across all clusters identified by k-means clustering (μ₁ = μ₂ = μ₃ = μ₄ = μ₅).

  • H1: At least one cluster has a mean age that is different from the others (At least one μₐge is not equal to the others).

BMI:
  • H0: The mean BMI is the same across all clusters identified by k-means clustering (μ₁ = μ₂ = μ₃ = μ₄ = μ₅)

  • H1: At least one cluster has a mean BMI that is different from the others (At least one μBMI is not equal to the others).

Children:
  • H0: The mean number of children covered by insurance is the same across all clusters identified by k-means clustering (μ₁ = μ₂ = μ₃ = μ₄ = μ₅).

  • H1: At least one cluster has a mean number of children that is different from the others (At least one μChildren is not equal to the others).

Medical Cost:
  • H0: The mean medical cost is the same across all clusters identified by k-means clustering (μ₁ = μ₂ = μ₃ = μ₄ = μ₅).

  • H1: At least one cluster has a mean medical cost that is different from the others (At least one μMedicalCost is not equal to the others).

Based on the p-values (all: p<0.001), I can reject the H0 for all four cluster variables, as they all have at least one mean different from the others.

###Smoker/NonSmoker

chi_square <- chisq.test(mydata$Smoker, as.factor(mydata$ClusterK_Means2))
chi_square
## 
##  Pearson's Chi-squared test
## 
## data:  mydata$Smoker and as.factor(mydata$ClusterK_Means2)
## X-squared = 188.29, df = 4, p-value < 2.2e-16

H0: There is no association between the variables.

H1: There is association between the variables

addmargins(chi_square$observed)
##              
## mydata$Smoker   1   2   3   4   5 Sum
##    Smoker      20  14  11  11  49 105
##    Non-smoker  92  84 102 108   3 389
##    Sum        112  98 113 119  52 494
addmargins(round(chi_square$expected, 2)) 
##              
## mydata$Smoker      1     2      3      4     5 Sum
##    Smoker      23.81 20.83  24.02  25.29 11.05 105
##    Non-smoker  88.19 77.17  88.98  93.71 40.95 389
##    Sum        112.00 98.00 113.00 119.00 52.00 494
round(chi_square$res, 2) 
##              
## mydata$Smoker     1     2     3     4     5
##    Smoker     -0.78 -1.50 -2.66 -2.84 11.41
##    Non-smoker  0.41  0.78  1.38  1.48 -5.93
library(effectsize)
effectsize::cramers_v(mydata$Smoker, mydata$ClusterK_Means2)
## Cramer's V (adj.) |       95% CI
## --------------------------------
## 0.61              | [0.53, 1.00]
## 
## - One-sided CIs: upper bound fixed at [1.00].
interpret_cramers_v(0.61)
## [1] "very large"
## (Rules: funder2019)

H0: There is no association between the variables.

H1: There is association between the variables.

  • With this ChiSquared test we are testing if there is a statistically significant association between smoking/not-smoking and the cluster groups. I can reject the null hypothesis at p<0,001, which indicates that there is association.

Interpreting one group of standardized residuals (interpretation of group 5):

  • For Group 5, there’s more than expected number of smokers and less than expected non-smokers at alpha=0.001.

Alpha of 0.05 corresponds value of approximately ±1.96.

Alpha of 0.01 corresponds value of approximately ±2.58.

Alpha of 0.001 corresponds to a value of approximately ±3.29.

Gender:

chi_square <- chisq.test(mydata$Gender, as.factor(mydata$ClusterK_Means2))
chi_square
## 
##  Pearson's Chi-squared test
## 
## data:  mydata$Gender and as.factor(mydata$ClusterK_Means2)
## X-squared = 8.9575, df = 4, p-value = 0.06217
addmargins(chi_square$observed)
##              
## mydata$Gender   1   2   3   4   5 Sum
##        female  49  50  65  58  18 240
##        male    63  48  48  61  34 254
##        Sum    112  98 113 119  52 494
addmargins(round(chi_square$expected, 2)) 
##              
## mydata$Gender      1     2     3      4     5    Sum
##        female  54.41 47.61  54.9  57.81 25.26 239.99
##        male    57.59 50.39  58.1  61.19 26.74 254.01
##        Sum    112.00 98.00 113.0 119.00 52.00 494.00
round(chi_square$res, 2) 
##              
## mydata$Gender     1     2     3     4     5
##        female -0.73  0.35  1.36  0.02 -1.45
##        male    0.71 -0.34 -1.33 -0.02  1.40
library(effectsize)
effectsize::cramers_v(mydata$Gender, mydata$ClusterK_Means2)
## Cramer's V (adj.) |       95% CI
## --------------------------------
## 0.10              | [0.00, 1.00]
## 
## - One-sided CIs: upper bound fixed at [1.00].
interpret_cramers_v(0.10)
## [1] "small"
## (Rules: funder2019)

H0: There is no assiciation between the variables.

H1: There is association between the variables.

  • With this ChiSquared test we are testing if there is a statistically significant association between the genders and the clustering groups. We fail to reject null hypothesis at p=0.06, indicating there is no association between the cluster variables.
Region:
chi_square <- chisq.test(mydata$Region, as.factor(mydata$ClusterK_Means2))
chi_square
## 
##  Pearson's Chi-squared test
## 
## data:  mydata$Region and as.factor(mydata$ClusterK_Means2)
## X-squared = 156.74, df = 12, p-value < 2.2e-16
addmargins(chi_square$observed)
##              
## mydata$Region   1   2   3   4   5 Sum
##     Northeast  62  16  21  20  10 129
##     Southeast   0  31  39  48  22 140
##     Southwest   0  34  36  29  12 111
##     Northwest  50  17  17  22   8 114
##     Sum       112  98 113 119  52 494
addmargins(round(chi_square$expected, 2)) 
##              
## mydata$Region      1     2      3      4     5    Sum
##     Northeast  29.25 25.59  29.51  31.07 13.58 129.00
##     Southeast  31.74 27.77  32.02  33.72 14.74 139.99
##     Southwest  25.17 22.02  25.39  26.74 11.68 111.00
##     Northwest  25.85 22.62  26.08  27.46 12.00 114.01
##     Sum       112.01 98.00 113.00 118.99 52.00 494.00
round(chi_square$res, 2) 
##              
## mydata$Region     1     2     3     4     5
##     Northeast  6.06 -1.90 -1.57 -1.99 -0.97
##     Southeast -5.63  0.61  1.23  2.46  1.89
##     Southwest -5.02  2.55  2.11  0.44  0.09
##     Northwest  4.75 -1.18 -1.78 -1.04 -1.15
library(effectsize)
effectsize::cramers_v(mydata$Region, mydata$ClusterK_Means2)
## Cramer's V (adj.) |       95% CI
## --------------------------------
## 0.31              | [0.26, 1.00]
## 
## - One-sided CIs: upper bound fixed at [1.00].

H0: There is no association between the variables.

H1: There is association between the variables.

  • With this ChiSquared test we are testing if there ia a statistically significant association between the regions and the clustering groups. We reject the H0 at p < 0.001, which indicates that there is statistically significant association.

When looking at the standardized residuals we can see that (interpretation of 2 groups ):

  • there are more than expected beneficiaries from the northeast and less than expected people from the southwest in the 1st group at alpha = 0.001.

  • more than expected beneficiaries from southeast in the 4th group and less than expected in northeast in group 4 at alpha = 0.01

Alpha of 0.05 corresponds value of approximately ±1.96.

Alpha of 0.01 corresponds value of approximately ±2.58.

Alpha of 0.001 corresponds to a value of approximately ±3.29.

interpret_cramers_v(0.31)
## [1] "large"
## (Rules: funder2019)

Conclusion

In this clustering analysis I performed hierarchical clustering of 494 units based on 4 cluster variables. This was done with the use of Euclidean squared distance and WARD’s algorithm. The classification was also further optimized by the K-means clustering method. I also found outliers and had to remove them, rescale the data and perform clustering again.

Description of Group 1:

Group 1 contains the second most people ((112/494)*100=22,67%) with 112 units, around average old with slightly above average number children, with the highest BMI - significantly above the average, and medical costs that are below average. More than expected beneficiaries from the northeast and less than expected people from the southwest in the 1st group at alpha = 0.001. For Group 5, there’s more than expected number of smokers and less than expected non-smokers at alpha=0.001. Also there is no association with the variables and gender, since the p value is > 0.05.