mydata <- read.table("./insurance.csv", fill=TRUE, header=TRUE, sep=",")
mydata <- mydata[,c(1, 2, 3, 4, 5, 7)]
set.seed(100)
mydata <- mydata[sample(nrow(mydata), 300), ]
# Dropping missing values
library(tidyr)
mydata <- drop_na(mydata)
#Factoring categorical variables Smoker and Sex
mydata$smoker <- factor(mydata$smoker,
levels = c("yes", "no"),
labels = c("yes", "no"))
mydata$sex <- factor(mydata$sex,
levels = c("male", "female"),
labels = c("male", "female"))
# Renaming columns
colnames(mydata) <- c("age", "gender", "bmi", "children", "smoker", "charges")
# Adding ID Column in case I will need to drop units later
mydata$ID <- seq(nrow(mydata))
# Reordering the data frame so that ID column is the first one
mydata <- mydata[ , c("ID", names(mydata)[names(mydata) != "ID"])]
#Showing table with first 10 rows
head(mydata, 10)
## ID age gender bmi children smoker charges
## 1 1 51 male 23.210 1 yes 22218.115
## 2 2 20 male 30.115 5 no 4915.060
## 3 3 48 male 29.600 0 no 21232.182
## 4 4 61 female 28.200 0 no 13041.921
## 5 5 18 female 24.090 1 no 2201.097
## 6 6 18 female 31.130 0 no 1621.883
## 7 7 56 female 28.310 0 no 11657.719
## 8 8 46 male 38.170 2 no 8347.164
## 9 9 26 male 27.265 3 no 4661.286
## 10 10 46 female 23.655 1 yes 21677.283
DESCRIPTION OF VARIABLES
age: age of insured person - in years (numerical).
sex: gender male or female (binary).
bmi: body mass index of insured person (numerical).
children: number of children of insured pearson (numerical).
smoker: if the insured person smokes or not (binary).
charges: cost of medical charges for individual insured person (numerical).
Unit of observation is a person who is insured. Sample size at the beginning is 300 with 6 variables (without ID).
Source of the Data set : Kaggle | Medical Cost Personal Datasets
#Showing some descriptive statistics
summary(mydata[,-1])
## age gender bmi children smoker
## Min. :18.00 male :143 Min. :16.82 Min. :0.00 yes: 62
## 1st Qu.:28.75 female:157 1st Qu.:27.19 1st Qu.:0.00 no :238
## Median :42.00 Median :31.16 Median :1.00
## Mean :40.94 Mean :30.96 Mean :1.02
## 3rd Qu.:53.25 3rd Qu.:34.91 3rd Qu.:2.00
## Max. :64.00 Max. :47.52 Max. :5.00
## charges
## Min. : 1136
## 1st Qu.: 5238
## Median :10295
## Mean :13360
## 3rd Qu.:15971
## Max. :52591
Age: Minimum age is 18, while maximum is 64. 50% of people have 42 years or less, the rest are older than 42. Gender: There are 143 women and 157 men. BMI: Minimum value for bmi is 16.82, while maximum is 47.52. 25% of people have a bmi value score of 27.19 or less. 50% of units have a bmi value of 31.16 or less. Charges: Interquartile range for charges is 10733.
mydata$age <- as.integer(mydata$age)
mydata$bmi <- as.integer(mydata$bmi)
mydata$children <- as.integer(mydata$children)
mydata$charges <- as.integer(mydata$charges)
For the purpose of this clustering I will choose only numeric variables.
#I will firstly do standardization to achieve that all cluster variables contribute equally to my results.
mydata$Age_z <- scale(mydata$age)
mydata$Bmi_z <- scale(mydata$bmi)
mydata$Children_z <- scale(mydata$children)
mydata$Charges_z <- scale(mydata$charges)
#Performing Pearson Correlation
library(Hmisc)
##
## Attaching package: 'Hmisc'
## The following objects are masked from 'package:base':
##
## format.pval, units
rcorr(as.matrix(mydata[, c("Age_z", "Bmi_z", "Children_z", "Charges_z")]),
type = "pearson")
## Age_z Bmi_z Children_z Charges_z
## Age_z 1.00 0.15 -0.06 0.31
## Bmi_z 0.15 1.00 0.06 0.15
## Children_z -0.06 0.06 1.00 -0.02
## Charges_z 0.31 0.15 -0.02 1.00
##
## n= 300
##
##
## P
## Age_z Bmi_z Children_z Charges_z
## Age_z 0.0114 0.3402 0.0000
## Bmi_z 0.0114 0.2797 0.0089
## Children_z 0.3402 0.2797 0.6754
## Charges_z 0.0000 0.0089 0.6754
From what I can observe on the Correlation Matrix, there is semi strong correlation between Charges and Age (all others are weak or very weak); this all together is good because we don’t want too excessive correlation between variables.
# I showed 10 units with highest dissimilarity to check possible outliers; by descending order
mydata$Dissimilarity <- sqrt(mydata$Age_z^2 + mydata$Bmi_z^2 + mydata$Children_z^2 + mydata$Charges_z^2)
head(mydata[order(-mydata$Dissimilarity), ], 10)
## ID age gender bmi children smoker charges Age_z Bmi_z
## 256 256 33 male 42 5 no 6666 -0.5551975 1.94048849
## 298 298 60 male 32 0 yes 52590 1.3327537 0.25895600
## 155 155 64 male 36 2 yes 49577 1.6124502 0.93156900
## 2 2 20 male 30 5 no 4915 -1.4642110 -0.07735049
## 63 63 19 male 44 0 yes 39722 -1.5341351 2.27679499
## 70 70 64 male 33 0 yes 46889 1.6124502 0.42710925
## 183 183 33 male 33 5 no 6653 -0.5551975 0.42710925
## 175 175 18 female 42 0 yes 38792 -1.6040593 1.94048849
## 198 198 58 male 36 2 yes 47496 1.1929054 0.93156900
## 169 169 39 female 34 5 no 8596 -0.1356528 0.59526250
## Children_z Charges_z Dissimilarity
## 256 3.3506124 -0.5837889 3.954890
## 298 -0.8586997 3.4214639 3.779824
## 155 0.8250252 3.1586857 3.758428
## 2 3.3506124 -0.7365020 3.730809
## 63 -0.8586997 2.2991838 3.682523
## 70 -0.8586997 2.9242523 3.474339
## 183 3.3506124 -0.5849227 3.472665
## 175 -0.8586997 2.2180740 3.463484
## 198 0.8250252 2.9771917 3.440230
## 169 3.3506124 -0.4154643 3.431028
I can observe a significant change from units with ID 70 and above (from 3.47 to 3.68); therefore I will remove the units with dissimilarity more than 3.5.
mydata <- mydata[mydata$Dissimilarity < 3.5,]
#Since I removed 5 units, I need to restandardize variables.
mydata$Age_z <- scale(mydata$age)
mydata$Bmi_z <- scale(mydata$bmi)
mydata$Children_z <- scale(mydata$children)
mydata$Charges_z <- scale(mydata$charges)
#Calculating Euclidean distances and squared Euclidean distances
library(factoextra)
## Loading required package: ggplot2
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
distance <- get_dist(mydata[c("Age_z", "Bmi_z", "Children_z", "Charges_z")],
method = "euclidian")
distance2 <- distance^2
fviz_dist(distance2)
Some natural groupings appear to be emerging based on what I can see. In order to verify whether the data is indeed clusterable, I will use Hopkins statistics.
#Calculating Hopkins statistics
get_clust_tendency(mydata[c("Age_z", "Bmi_z", "Children_z", "Charges_z")],
n = nrow(mydata) - 1,
graph = FALSE)
## $hopkins_stat
## [1] 0.75121
##
## $plot
## NULL
Hopkins statistics is 0.75 (cut-point is 0.5) which means that data is clusterable.
#Starting the hierarchical clustering
WARD <- mydata[c("Age_z", "Bmi_z", "Children_z", "Charges_z")] %>%
get_dist(method = "euclidean") %>%
hclust(method = "ward.D2")
print(WARD)
##
## Call:
## hclust(d = ., method = "ward.D2")
##
## Cluster method : ward.D2
## Distance : euclidean
## Number of objects: 295
After removing the units, I have 295 of them, they must be divided into groups.
#Dendrogram
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)
I will choose 5 cluster groups based on the Dendrogram above.
#Getting CLusterWard to see to which cluster group was unit clustered
mydata$ClusterWard <- cutree(WARD,
k = 5)
head(mydata)
## ID age gender bmi children smoker charges Age_z Bmi_z Children_z
## 1 1 51 male 23 1 yes 22218 0.7064181 -1.2469739 0.002954596
## 3 3 48 male 29 0 no 21232 0.4951373 -0.2293880 -0.868651150
## 4 4 61 female 28 0 no 13041 1.4106876 -0.3989857 -0.868651150
## 5 5 18 female 24 1 no 2201 -1.6176713 -1.0773763 0.002954596
## 6 6 18 female 31 0 no 1621 -1.6176713 0.1098073 -0.868651150
## 7 7 56 female 28 0 no 11657 1.0585529 -0.3989857 -0.868651150
## Charges_z Dissimilarity ClusterWard
## 1 0.831453838 1.632654 1
## 3 0.741877410 1.229934 1
## 4 -0.002261045 1.696100 1
## 5 -0.987056656 2.168040 2
## 6 -1.039748672 2.089679 2
## 7 -0.127995097 1.428096 1
#Getting initial leaders, they will be reclassified with K-means later.
Initial_leaders <- aggregate(mydata[, c("Age_z", "Bmi_z", "Children_z", "Charges_z")],
by = list(mydata$ClusterWard),
FUN = mean)
Initial_leaders
## Group.1 Age_z Bmi_z Children_z Charges_z
## 1 1 0.93530573 -0.8383978 -0.41303906 0.4266978
## 2 2 -0.90488860 -0.3635752 -0.54299626 -0.5754489
## 3 3 0.81499302 0.8777078 -0.25126375 -0.2024844
## 4 4 -0.29315035 -0.2412896 1.51679615 -0.4436930
## 5 5 -0.02511343 0.6623674 -0.02516172 2.3696944
#Final K-Means clustering (I will not change them later).
K_MEANS <- hkmeans(mydata[, c("Age_z", "Bmi_z", "Children_z", "Charges_z")],
k = 5,
hc.metric = "euclidean",
hc.method = "ward.D2")
K_MEANS
## Hierarchical K-means clustering with 5 clusters of sizes 56, 72, 75, 61, 31
##
## Cluster means:
## Age_z Bmi_z Children_z Charges_z
## 1 0.64856742 -0.91080716 -0.43284828 0.3426591
## 2 -1.14424565 -0.47671793 -0.51758772 -0.7319193
## 3 0.70360106 0.81533354 -0.42703757 -0.2310583
## 4 -0.09714184 0.05976209 1.54612543 -0.3708505
## 5 -0.02511343 0.66236739 -0.02516172 2.3696944
##
## Clustering vector:
## 1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
## 1 1 1 2 2 1 3 4 1 4 5 2 3 4 3 3 1 3 1 1
## 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
## 5 1 4 4 4 3 2 2 4 3 4 1 2 1 3 2 2 2 3 3
## 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
## 4 2 5 1 2 2 4 1 1 2 5 4 2 4 1 4 4 2 2 3
## 62 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
## 3 2 3 2 4 1 1 5 5 3 3 3 2 3 4 4 3 4 2 3
## 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
## 4 5 2 4 5 2 1 1 4 1 2 2 5 2 1 2 4 3 2 3
## 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
## 5 3 2 2 4 1 3 2 3 2 1 2 3 4 1 5 3 3 2 4
## 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
## 2 3 4 3 3 4 1 2 2 4 1 4 1 3 4 1 5 1 3 2
## 143 144 145 146 147 148 149 150 151 152 153 154 156 157 158 159 160 161 162 163
## 1 2 3 3 5 4 1 3 2 4 2 3 1 5 2 1 4 1 5 2
## 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
## 2 3 2 3 4 4 3 3 1 4 2 5 4 3 4 3 5 2 3 4
## 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
## 1 1 3 3 2 2 4 3 1 5 4 3 3 3 5 3 5 2 4 4
## 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
## 5 3 2 1 4 3 1 3 2 3 3 2 2 2 2 4 5 1 4 2
## 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
## 3 4 2 4 4 1 4 4 4 1 5 2 4 4 1 3 2 5 1 4
## 244 245 246 247 248 249 250 251 252 253 254 255 257 258 259 260 261 262 263 264
## 1 3 3 3 2 3 5 3 3 5 5 3 4 4 3 1 3 3 5 3
## 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
## 1 2 2 2 1 2 2 3 2 2 4 4 5 2 1 2 3 1 3 1
## 285 286 287 288 289 290 291 292 293 294 295 296 297 299 300
## 4 1 1 3 5 5 2 2 2 1 4 3 3 1 3
##
## Within cluster sum of squares by cluster:
## [1] 81.07287 103.60916 92.23930 128.44456 67.67322
## (between_SS / total_SS = 59.8 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss"
## [6] "betweenss" "size" "iter" "ifault" "data"
## [11] "hclust"
There are 5 clusters: In the 1st cluster there are 56 people, 2nd 72 people, 3rd 75 people, 4th 61 people, 5th 31 people. Cluster means refers to the information of each variable’s mean value for each cluster. Clustering vector shows that the first person is in the first group, the fifth person is in the second group, and so on (which individual is in which cluster).
The clusters appear to be relatively homogeneous (59.8%), which the ratio of between SS and total SS shows; it indicates the degree of variation in units within and across groups. This should be as near to 100% as possible.
#Showing plot graphically
fviz_cluster(K_MEANS,
palette = "jama",
repel = FALSE,
ggtheme = theme_classic())
From the Cluster Plot above, I have 5 groups, there are no significant
outliers, and I am not paying attention to overlapping because this is a
two dimensional plot and so it doesn’t show all information.
mydata$ClusterK_Means <- K_MEANS$cluster
head(mydata[c("ID","ClusterWard", "ClusterK_Means")], 20)
## ID ClusterWard ClusterK_Means
## 1 1 1 1
## 3 3 1 1
## 4 4 1 1
## 5 5 2 2
## 6 6 2 2
## 7 7 1 1
## 8 8 3 3
## 9 9 4 4
## 10 10 1 1
## 11 11 4 4
## 12 12 5 5
## 13 13 2 2
## 14 14 3 3
## 15 15 4 4
## 16 16 3 3
## 17 17 2 3
## 18 18 1 1
## 19 19 3 3
## 20 20 1 1
## 21 21 1 1
Up to the 17th person, there were no reclassifications using K-Means clustering, from the data frame above we can see that 17th person was reclassified from the group 2 to the group 3.
#Showing initial Cluster size
table(mydata$ClusterWard)
##
## 1 2 3 4 5
## 44 91 72 57 31
#Showing cluster size after K-Means
table(mydata$ClusterK_Means)
##
## 1 2 3 4 5
## 56 72 75 61 31
table(mydata$ClusterWard, mydata$ClusterK_Means)
##
## 1 2 3 4 5
## 1 41 0 2 1 0
## 2 14 67 9 1 0
## 3 0 0 64 8 0
## 4 1 5 0 51 0
## 5 0 0 0 0 31
As this table shows:
#Getting final centroids
Centroids <- K_MEANS$centers
Centroids
## Age_z Bmi_z Children_z Charges_z
## 1 0.64856742 -0.91080716 -0.43284828 0.3426591
## 2 -1.14424565 -0.47671793 -0.51758772 -0.7319193
## 3 0.70360106 0.81533354 -0.42703757 -0.2310583
## 4 -0.09714184 0.05976209 1.54612543 -0.3708505
## 5 -0.02511343 0.66236739 -0.02516172 2.3696944
#Showing the plot to profile groups and trends across clustered variables
library(ggplot2)
library(tidyr)
Figure <- as.data.frame(Centroids)
Figure$id <- 1:nrow(Figure)
Figure <- pivot_longer(Figure, cols = c("Age_z", "Bmi_z", "Children_z", "Charges_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("Age_z", "Bmi_z", "Children_z", "Charges_z"),
labels = c("Age_z", "Bmi_z", "Children_z", "Charges_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(-2.0, 2.5)
People in group 1: People are older than the average and and spend more money on average on medical charges; they have bmi below average and less children than the average.
People in group 2: This group is below average in all values (age, bmi, number of children and medical charges).
People in group 3: People in this group are above average in age and bmi value, but have less children and medical charges cost less than the average.
People in group 4: This group is around average in age and bmi value and well above average in the number of children they have, except for charges - they have spent less.
People in group 5: People in this group are average in age and number of children, but have higher bmi value medical charges and costs above the average.
# All one-way ANOVAs at once
fit <- aov(cbind(Age_z, Bmi_z, Children_z, Charges_z) ~ as.factor(ClusterK_Means),
data = mydata)
summary(fit)
## Response 1 :
## Df Sum Sq Mean Sq F value Pr(>F)
## as.factor(ClusterK_Means) 4 155.55 38.887 81.454 < 2.2e-16 ***
## Residuals 290 138.45 0.477
## ---
## 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) 4 126.5 31.624 54.75 < 2.2e-16 ***
## Residuals 290 167.5 0.578
## ---
## 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) 4 189.3 47.325 131.08 < 2.2e-16 ***
## Residuals 290 104.7 0.361
## ---
## 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) 4 231.619 57.905 269.19 < 2.2e-16 ***
## Residuals 290 62.381 0.215
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Based on sample data I can reject the null hypothesis (Ho:the mean age of individuals is the same across all clusters) at p<0.001. H1:At least one cluster has a mean age that is different than the others.
ANOVA test is significant; every variable I choose has statistical significance; means of the variables differ across the groups. I came to the conclusion that every cluster variable successfully groups units into clusters.
#For the categorical variables I need to preform Pearson`s chi-squared test
chisq_results <- chisq.test(mydata$smoker, as.factor(mydata$ClusterK_Means))
chisq_results
##
## Pearson's Chi-squared test
##
## data: mydata$smoker and as.factor(mydata$ClusterK_Means)
## X-squared = 138.71, df = 4, p-value < 2.2e-16
Based on the sample data, I can reject the null hypothesis (p<0.001) based on H0: There is no association between the variables; H1: There is association between the variables.
addmargins(chisq_results$observed)
##
## mydata$smoker 1 2 3 4 5 Sum
## yes 21 7 0 3 28 59
## no 35 65 75 58 3 236
## Sum 56 72 75 61 31 295
round(chisq_results$expected, 2)
##
## mydata$smoker 1 2 3 4 5
## yes 11.2 14.4 15 12.2 6.2
## no 44.8 57.6 60 48.8 24.8
All expected frequencies are above 5. Assumptions are met.
round(chisq_results$res, 2)
##
## mydata$smoker 1 2 3 4 5
## yes 2.93 -1.95 -3.87 -2.63 8.76
## no -1.46 0.98 1.94 1.32 -4.38
For row number 1 and column 5 the standardized residual is 8.76. This shows that I have observed more people in this group than expected (at alpha = 0.1%). In the group 2, there are no significant deviations from what I expected to see because all residuals are within (+/- 1,96, alpha = 0.05%).
library(effectsize)
effectsize::cramers_v(mydata$smoker, mydata$ClusterK_Means)
## Cramer's V (adj.) | 95% CI
## --------------------------------
## 0.68 | [0.57, 1.00]
##
## - One-sided CIs: upper bound fixed at [1.00].
Effect size is very large ( r>=0.4).
chisq_results <- chisq.test(mydata$gender, as.factor(mydata$ClusterK_Means))
chisq_results
##
## Pearson's Chi-squared test
##
## data: mydata$gender and as.factor(mydata$ClusterK_Means)
## X-squared = 5.6393, df = 4, p-value = 0.2278
Based on the sample data, I can not reject the null hypothesis (p=0.2278), which states that there is no association between gender and the groups. That is why I will not further analyze gender and clusters.
Classification of 295 people was based on four standardized variables.
For hierarchical clustering, I used Ward’s clustering algorithm and decided to divide them into 5 cluster groups based on the analysis of the dendrogram. The classification was further optimized using the K-Means cluster.
Cluster 1 (56/295(18,98%) of all people) represents the fourth largest group. They have lowest means on bmi and number of children, while highest on age and charges.
To answer my research question: I have successfully divided medical beneficiaries into 5 homogeneous groups based on age, BMI, number of children and medical charges. For validation I have smoking, while gender was not a good variable for it. If we take group 2: This group is below average in all values (age, bmi, number of children and medical charges). Which if we look at the insurance company`s point of view would make a great target group. Here we also see 24.8 less people that are smokers than expected. Standardized residuals for non smoker and column 5, the standardized residual is -4.38. This shows that i have observed less people in this group than expected (at alpha = 0.1%).