This dataset contains information about married people in US and connecting their description with affairs.
Source of data: Kaggle
(Url:https://www.kaggle.com/datasets/kashnitsky/mlcourse/data?select=affairs.csv)
#importing data
mydata <- read_csv("~/Desktop/IMB/Multivariate /HW/H4/affairs.csv")
## New names:
## Rows: 6366 Columns: 10
## โโ Column specification
## โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Delimiter: "," dbl
## (10): ...1, rate_marriage, age, yrs_married, children, religious, educ, occupation, occupation_husb, affairs
## โน 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.
## โข `` -> `...1`
#selecting random 800 units
set.seed(6)
mydata <- mydata[sample(nrow(mydata), 800), ]
#removing variable
mydata <- mydata[, c(-1,-9,-8)]
#creating new variable ID
mydata$ID <- 1:nrow(mydata)
mydata <- mydata[, c("ID", names(mydata)[-length(mydata)])]
head(mydata)
## # A tibble: 6 ร 8
## ID rate_marriage age yrs_married children religious educ affairs
## <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 1 3 42 23 3 3 14 0
## 2 2 3 22 2.5 0 2 16 1.40
## 3 3 3 37 16.5 4 3 12 1.19
## 4 4 4 22 2.5 0 3 17 0
## 5 5 3 27 9 2 2 14 0
## 6 6 3 37 23 3 2 12 0.852
Unit of observation: one person
Sample size: 1000
Number of variables: 8
Description of dataset:
ID: Identification variable
rate marriage: how people rate their marriage on a scale from 1 to 5, one meaning very bad and 5 meaning very good
age: age of a person
years married: for how many years people have been married
children: number of children people have
religious: how religious people are on a scale from 1 to 4, one meaning not religious and 4 meaning very religious
education: years spent in an education program
affairs: number of affair in one year of marriage
summary(mydata)
## ID rate_marriage age yrs_married children religious educ
## Min. : 1.0 Min. :1.000 Min. :17.50 Min. : 0.500 Min. :0.000 Min. :1.000 Min. : 9.00
## 1st Qu.:200.8 1st Qu.:4.000 1st Qu.:22.00 1st Qu.: 2.500 1st Qu.:0.000 1st Qu.:2.000 1st Qu.:12.00
## Median :400.5 Median :4.000 Median :27.00 Median : 6.000 Median :1.000 Median :2.000 Median :14.00
## Mean :400.5 Mean :4.136 Mean :29.11 Mean : 9.117 Mean :1.435 Mean :2.417 Mean :14.19
## 3rd Qu.:600.2 3rd Qu.:5.000 3rd Qu.:32.00 3rd Qu.:16.500 3rd Qu.:2.000 3rd Qu.:3.000 3rd Qu.:16.00
## Max. :800.0 Max. :5.000 Max. :42.00 Max. :23.000 Max. :5.500 Max. :4.000 Max. :20.00
## affairs
## Min. : 0.0000
## 1st Qu.: 0.0000
## Median : 0.0000
## Mean : 0.5517
## 3rd Qu.: 0.3889
## Max. :17.9200
The youngest person in the dataset is 17,5 years old and the oldest is 42. 50% of people are older than 27 and 50% are younger than 27.
The average rate marriage is 4,136. 75% of people in the sample rate their marriage more than 4 points and 25% less than 5 points.
The average marriage duration in the sample is 9.117 years. 25 % of employees are married for more than 16.5 years.
#standardizing variables for the to contribute equally to the final result
mydata$rate_marriage <- scale(mydata$rate_marriage)
mydata$yrs_married <- scale(mydata$yrs_married)
mydata$educ <- scale(mydata$educ)
mydata$affairs <- scale(mydata$affairs)
Correlation should be lower than 0.3 for clustering and as we can see bellow, the highers correlation in our data is affairs and rate marriage but it is still lower than 0.3.
library(Hmisc)
rcorr(as.matrix(mydata[, c("rate_marriage", "yrs_married", "educ", "affairs")]),
type = "pearson")
## rate_marriage yrs_married educ affairs
## rate_marriage 1.00 -0.13 0.10 -0.22
## yrs_married -0.13 1.00 -0.08 -0.06
## educ 0.10 -0.08 1.00 -0.01
## affairs -0.22 -0.06 -0.01 1.00
##
## n= 800
##
##
## P
## rate_marriage yrs_married educ affairs
## rate_marriage 0.0003 0.0042 0.0000
## yrs_married 0.0003 0.0174 0.0985
## educ 0.0042 0.0174 0.6805
## affairs 0.0000 0.0985 0.6805
We are looking for the highers dissimilarities and removing them.
mydata$Dissimilarity <- sqrt(mydata$rate_marriage^2 + mydata$yrs_married^2 + mydata$educ^2 + mydata$affairs^2) #Finding outliers
head(mydata[order(-mydata$Dissimilarity), ], 20
) #10 units with the highest value of dissimilarity
## # A tibble: 20 ร 9
## ID rate_marriage[,1] age yrs_married[,1] children religious educ[,1] affairs[,1] Dissimilarity[,1]
## <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 427 -2.32 27 -0.906 0 2 0.819 10.9 11.2
## 2 300 -0.148 22 -0.906 0 3 -0.0847 10.9 10.9
## 3 221 -1.23 27 -0.906 0 1 1.27 10.2 10.3
## 4 13 -2.32 22 -0.906 1 3 -0.0847 4.55 5.19
## 5 78 -1.23 22 -0.906 0 1 -0.0847 4.55 4.81
## 6 359 -0.148 27 -0.906 0 2 -0.989 4.55 4.75
## 7 225 -0.148 22 -0.906 0 2 0.819 4.55 4.72
## 8 440 -0.148 22 -0.906 1 3 -0.0847 4.55 4.65
## 9 792 -0.148 22 -0.906 1 2 -0.0847 4.55 4.65
## 10 488 -1.23 27 -0.0161 2 3 -0.989 4.32 4.60
## 11 717 -3.40 22 -0.906 0 1 -0.0847 2.72 4.45
## 12 724 0.938 22 -0.427 2 3 -0.0847 4.32 4.44
## 13 729 -0.148 27 -0.427 0 3 -0.0847 4.32 4.35
## 14 731 -0.148 22 -1.18 0 2 -0.989 4.03 4.32
## 15 667 -0.148 27 -0.427 1 1 -0.989 4.03 4.17
## 16 757 -2.32 42 1.90 1 1 2.63 0.872 4.08
## 17 594 -3.40 42 1.90 3 2 -0.989 -0.345 4.04
## 18 360 -3.40 32 0.531 2 2 1.27 1.67 4.04
## 19 435 -2.32 37 1.90 3 3 -0.989 2.26 3.88
## 20 108 -3.40 32 1.01 2 2 1.27 0.110 3.77
mydata <- mydata %>%
filter(Dissimilarity <= 4)
## Warning: Using one column matrices in `filter()` was deprecated in dplyr 1.1.0.
## โน Please use one dimensional logical vectors instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was generated.
Showing the dissimilarity matrix.
library(factoextra)
#Calculating Euclidean distances
distance <- get_dist(mydata[c("rate_marriage", "yrs_married", "educ", "affairs")],
method = "euclidian")
distance2 <- distance^2
fviz_dist(distance2)
We need to do the Hopkins test which needs to be higher than 0.5.
get_clust_tendency(mydata[c("rate_marriage", "yrs_married", "educ", "affairs")], #Hopkins statistics
n = nrow(mydata) - 1,
graph = FALSE)
## $hopkins_stat
## [1] 0.7344783
##
## $plot
## NULL
Here we calculate the average Euclidian squared distance and assigning the Ward algorithm.
library(dplyr)
WARD <- mydata[c("rate_marriage", "yrs_married", "educ", "affairs")] %>%
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: 782
Showing the dendrogram which suggest that we will cut it in a way, that we will get 3 clusters.
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 = 4,
cex = 0.5,
palette = "jama",
color_labels_by_k = TRUE,
rect = TRUE)
fviz_dend(WARD,
k = 3,
cex = 0.5,
palette = "jama",
color_labels_by_k = TRUE,
rect = TRUE)
mydata$ClusterWard <- cutree(WARD,
k = 3) #Cutting the dendrogram
head(mydata)
## # A tibble: 6 ร 10
## ID rate_marriage[,1] age yrs_married[,1] children religious educ[,1] affairs[,1] Dissimilarity[,1] ClusterWard
## <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <int>
## 1 1 -1.23 42 1.90 3 3 -0.0847 -0.345 2.29 1
## 2 2 -1.23 22 -0.906 0 2 0.819 0.530 1.81 2
## 3 3 -1.23 37 1.01 4 3 -0.989 0.398 1.92 1
## 4 4 -0.148 22 -0.906 0 3 1.27 -0.345 1.61 3
## 5 5 -1.23 27 -0.0161 2 2 -0.0847 -0.345 1.28 2
## 6 6 -1.23 37 1.90 3 2 -0.989 0.188 2.48 1
#Calculating positions of initial leaders
Initial_leaders <- aggregate(mydata[, c("rate_marriage", "yrs_married", "educ", "affairs")],
by = list(mydata$ClusterWard),
FUN = mean)
Initial_leaders
## Group.1 rate_marriage yrs_married educ affairs
## 1 1 -0.26325506 1.22023527 -0.6327435 -0.07722270
## 2 2 -0.02427193 -0.65093176 -0.3985861 -0.05125048
## 3 3 0.39230911 -0.05140784 1.2710816 -0.23576151
Performing K-Means clustering - initial leaders are chosen as centroids of groups, found with hierarhical clustering.
library(factoextra)
K_MEANS <- hkmeans(mydata[c("rate_marriage", "yrs_married", "educ", "affairs")],
k = 3,
hc.metric = "euclidean",
hc.method = "ward.D2")
K_MEANS
## Hierarchical K-means clustering with 3 clusters of sizes 237, 339, 206
##
## Cluster means:
## rate_marriage yrs_married educ affairs
## 1 -0.25781219 1.2635352 -0.4051014 -0.06354700
## 2 0.04102067 -0.6724960 -0.4993505 -0.08683466
## 3 0.33160317 -0.3120442 1.2820510 -0.19721556
##
## Clustering vector:
## [1] 1 3 1 3 2 1 2 2 1 1 1 2 2 1 1 1 2 3 1 2 3 1 2 1 2 1 1 2 2 2 1 1 3 2 2 3 2 2 3 3 1 2 1 1 3 2 1 3 2 2 3 3 2 1 2 1 2
## [58] 2 2 2 2 3 2 1 1 1 3 2 2 2 1 2 3 3 3 3 1 2 2 2 2 3 2 1 2 3 2 3 2 2 1 1 2 1 2 1 3 3 3 1 1 2 1 1 3 1 2 3 3 1 3 3 1 1
## [115] 2 2 2 3 3 2 1 3 1 1 1 1 1 1 3 1 2 3 2 1 3 1 3 3 2 2 2 3 2 3 1 1 2 3 3 3 3 2 1 1 2 2 3 3 2 2 3 2 3 2 1 1 1 2 1 2 2
## [172] 2 2 2 2 2 2 1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 2 3 2 2 3 1 1 2 2 2 2 3 2 1
## [685] 2 2 2 3 1 2 3 1 2 2 2 2 1 1 1 2 2 2 2 1 3 2 1 2 2 1 3 2 3 2 1 3 1 2 1 2 2 2 3 2 1 2 1 1 3 2 1 1 1 2 2 2 3 3 1 2 3
## [742] 3 1 3 2 3 3 3 1 3 3 3 1 2 2 2 3 3 3 2 3 2 2 3 2 2 2 2 2 3 1 1 1 2 2 2 3 2 3 2 1 1
##
## Within cluster sum of squares by cluster:
## [1] 574.9494 545.0959 358.4746
## (between_SS / total_SS = 41.6 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss" "betweenss" "size"
## [8] "iter" "ifault" "data" "hclust"
We can see that in the first cluster there are 237 people, in the second one 339 and the third 206.
total sum of squares = between SS (we want to maximize) + within SS (we want to minimize), we want the number as close to 100% as possible. In our case it is 40.1%, which is not the best, there is no a lot of variability between groups.
We can see that all initial leaders are different than final leaders.
fviz_cluster(K_MEANS,
palette = "jama",
repel = FALSE,
ggtheme = theme_classic())
We will do classification by K means.
mydata$ClusterK_Means <- K_MEANS$cluster
head(mydata[c("ID", "ClusterWard", "ClusterK_Means")])
## # A tibble: 6 ร 3
## ID ClusterWard ClusterK_Means
## <int> <int> <int>
## 1 1 1 1
## 2 2 2 3
## 3 3 1 1
## 4 4 3 3
## 5 5 2 2
## 6 6 1 1
#Checking for reclassifications
table(mydata$ClusterWard)
##
## 1 2 3
## 207 360 215
table(mydata$ClusterK_Means)
##
## 1 2 3
## 237 339 206
table(mydata$ClusterWard, mydata$ClusterK_Means)
##
## 1 2 3
## 1 202 5 0
## 2 7 334 19
## 3 28 0 187
In the first row with hierarchical method there used to be 207 units. With K-means, 5 units reclassified into the 2nd group.
in the second column with K-means there is 334 units. 5 of them were reclassified from group 1.
Centroids <- K_MEANS$centers
Centroids
## rate_marriage yrs_married educ affairs
## 1 -0.25781219 1.2635352 -0.4051014 -0.06354700
## 2 0.04102067 -0.6724960 -0.4993505 -0.08683466
## 3 0.33160317 -0.3120442 1.2820510 -0.19721556
library(ggplot2)
library(tidyr)
##
## Attaching package: 'tidyr'
## The following object is masked from 'package:magrittr':
##
## extract
Figure <- as.data.frame(Centroids)
Figure$id <- 1:nrow(Figure)
Figure <- pivot_longer(Figure, cols = c("rate_marriage", "yrs_married", "educ", "affairs"))
Figure$Groups <- factor(Figure$id,
levels = c(1, 2, 3, 4),
labels = c("1", "2", "3", "4"))
Figure$nameFactor <- factor(Figure$name,
levels = c("rate_marriage", "yrs_married", "educ", "affairs"),
labels = c("rate_marriage", "yrs_married", "educ", "affairs"))
ggplot(Figure, aes(x = nameFactor, y = value)) +
geom_hline(yintercept = 0) +
theme_bw() +
geom_point(aes(shape = Groups, col = Groups), size = 3) +
geom_line(aes(group = id), linewidth = 1) +
ylab("Averages") +
xlab("Cluster variables") +
ylim(-1.5, 1.5)
Group 1: 30,3%. We can see that people in group 1 are bellow average in marriage rate, above average in years of marriage, bellow average in education and below average in affairs in a year.
Group 2: 43,3%. People in group 2 are bellow average in marriage rate, affairs, and education. People in group 2 are above average in years of marriage
#Are all the cluster variables successful at classifing units into groups? Performing ANOVAs.
fit <- aov(cbind(rate_marriage, yrs_married, educ, affairs) ~ as.factor(ClusterK_Means),
data = mydata)
summary(fit)
## Response 1 :
## Df Sum Sq Mean Sq F value Pr(>F)
## as.factor(ClusterK_Means) 2 38.40 19.2025 21.263 1.021e-09 ***
## Residuals 779 703.51 0.9031
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Response 2 :
## Df Sum Sq Mean Sq F value Pr(>F)
## as.factor(ClusterK_Means) 2 551.68 275.840 935.84 < 2.2e-16 ***
## Residuals 779 229.61 0.295
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Response 3 :
## Df Sum Sq Mean Sq F value Pr(>F)
## as.factor(ClusterK_Means) 2 462.01 231.007 561.37 < 2.2e-16 ***
## Residuals 779 320.57 0.412
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Response 4 :
## Df Sum Sq Mean Sq F value Pr(>F)
## as.factor(ClusterK_Means) 2 2.259 1.12963 3.914 0.02036 *
## Residuals 779 224.832 0.28862
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
We will assume that homoscedasticy and normality are met.
We reject the H0 at p<0.001.
We reject the H0 at p<0.001.
We reject the H0 at p<0.001.
We reject the H0 at p=0.02.
aggregate(mydata$age,
by = list(mydata$ClusterK_Means),
FUN = "mean")
## Group.1 x
## 1 1 36.70464
## 2 2 24.38201
## 3 3 28.38592
fit <- aov(age ~ as.factor(ClusterK_Means),
data = mydata)
summary(fit)
## Df Sum Sq Mean Sq F value Pr(>F)
## as.factor(ClusterK_Means) 2 21353 10676 548.8 <2e-16 ***
## Residuals 779 15154 19
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
We reject H0 at p<0.001
We can say that in group 1 the average age is 36 years, in group 2 24 years and in group 3 28 years of age.
mydata$childrenF <- factor(mydata$children,
levels = c(0,1, 2, 3, 4),
labels = c("0","1","2", "3","4"
))
mydata <- mydata %>%
mutate(childrenF = ifelse(childrenF %in%
c("0"), "NoChildren", "Children"))
#Pearson Chi2 test
chisq_results <- chisq.test(mydata$childrenF, as.factor(mydata$ClusterK_Means))
chisq_results
##
## Pearson's Chi-squared test
##
## data: mydata$childrenF and as.factor(mydata$ClusterK_Means)
## X-squared = 179.87, df = 2, p-value < 2.2e-16
addmargins(chisq_results$observed)
##
## mydata$childrenF 1 2 3 Sum
## Children 231 155 101 487
## NoChildren 6 184 105 295
## Sum 237 339 206 782
round(chisq_results$expected, 2)
##
## mydata$childrenF 1 2 3
## Children 147.59 211.12 128.29
## NoChildren 89.41 127.88 77.71
round(chisq_results$res, 2)
##
## mydata$childrenF 1 2 3
## Children 6.87 -3.86 -2.41
## NoChildren -8.82 4.96 3.10
For categorical variables we use Pearson Chi squared test
We can reject the H0 at p<0.001 and conclude that there is association.
There is more than expected people with children in group 1 (๐ผ = 0,001), and more than expected people without children in groups 2 and 3 (๐ผ = 0,001).
mydata$religiousF <- factor(mydata$religious,
levels = c(1, 2, 3, 4),
labels = c("1","2", "3","4"
))
mydata <- mydata %>%
mutate(religiousF = case_when(
religiousF %in% c("1") ~ "NotReligious",
religiousF %in% c("2", "3") ~ "SemiReligious",
TRUE ~ "VeryReligious "
))
#Pearson Chi2 test
chisq_results1 <- chisq.test(mydata$religiousF, as.factor(mydata$ClusterK_Means))
chisq_results
##
## Pearson's Chi-squared test
##
## data: mydata$childrenF and as.factor(mydata$ClusterK_Means)
## X-squared = 179.87, df = 2, p-value < 2.2e-16
addmargins(chisq_results1$observed)
##
## mydata$religiousF 1 2 3 Sum
## NotReligious 28 66 40 134
## SemiReligious 181 243 140 564
## VeryReligious 28 30 26 84
## Sum 237 339 206 782
round(chisq_results1$expected, 2)
##
## mydata$religiousF 1 2 3
## NotReligious 40.61 58.09 35.30
## SemiReligious 170.93 244.50 148.57
## VeryReligious 25.46 36.41 22.13
round(chisq_results1$res, 2)
##
## mydata$religiousF 1 2 3
## NotReligious -1.98 1.04 0.79
## SemiReligious 0.77 -0.10 -0.70
## VeryReligious 0.50 -1.06 0.82
We can reject the H0 at p<0.001 and conclude that there is association.
There is more than expected people who are not religious in group 1 (๐ผ = 0,05), and more than expected people who are very religious in groups 1(๐ผ = 0,05) and 3 (๐ผ = 0,001).
Classification of 800 people was based on four standardized variables. For hierarchical clustering, Wardโs algorithm was used, and based on the analysis of the dendrogram it was decided to classify the students into 3 groups. The second group was the largest (43,4%).