#install.packages(ggplot2)
#library(ggplot2)
#install.packages("ggfortify")
#library(ggfortify)
#install.packages("ranger")
#library(ranger)
#install.packages("dplyr")
#library(dplyr)
#install.packages("Hmisc")
#library(Hmisc)
#install.packages("factoextra")
#library(factoextra)
#install.packages("cluster")
#library(cluster)
#install.packages("magrittr")
#library(magrittr)
#install.packages("NbClust")
#library("NbClust")
library(readxl)
mydata <- read_excel("~/Desktop/IMB/MVA/R homeworks/R homeworks/CarPrice_Assignment.xlsx")
head(mydata)
## # A tibble: 6 × 8
## ID `Fuel type` `Engine location` `Wheel base` Horsepower `Peak rpm` `Highway mpg` Price
## <dbl> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 1 gas front 88.6 111 5000 27 13495
## 2 2 gas front 88.6 111 5000 27 16500
## 3 3 gas front 94.5 154 5000 26 16500
## 4 4 gas front 99.8 102 5500 30 13950
## 5 5 gas front 99.4 115 5500 22 17450
## 6 6 gas front 99.8 110 5500 25 15250
The data covers cars, their prices and characteristics. There are 205 units in the sample and 7 variables (+ ID).
5 cluster variables will be used to classify cars into groups:
2 variables are used to validate groups:
#Factoring variables
mydata$`Fuel type` <- factor(mydata$`Fuel type`,
levels = c("gas", "diesel"),
labels = c("gas", "diesel"))
mydata$`Engine location` <- factor(mydata$`Engine location`,
levels = c("rear", "front"),
labels = c("rear", "front"))
summary(mydata)
## ID Fuel type Engine location Wheel base Horsepower Peak rpm Highway mpg
## Min. : 1 gas :185 rear : 3 Min. : 86.60 Min. : 48.0 Min. :4150 Min. :16.00
## 1st Qu.: 52 diesel: 20 front:202 1st Qu.: 94.50 1st Qu.: 70.0 1st Qu.:4800 1st Qu.:25.00
## Median :103 Median : 97.00 Median : 95.0 Median :5200 Median :30.00
## Mean :103 Mean : 98.76 Mean :104.1 Mean :5125 Mean :30.75
## 3rd Qu.:154 3rd Qu.:102.40 3rd Qu.:116.0 3rd Qu.:5500 3rd Qu.:34.00
## Max. :205 Max. :120.90 Max. :288.0 Max. :6600 Max. :54.00
## Price
## Min. : 5118
## 1st Qu.: 7788
## Median :10295
## Mean :13277
## 3rd Qu.:16503
## Max. :45400
Descriptive statistics:
#Standardizing the cluster variables
mydata$wheelbase <- scale(mydata$`Wheel base`)
mydata$horsepower <- scale(mydata$Horsepower)
mydata$peakrpm <- scale(mydata$`Peak rpm`)
mydata$highwaympg <- scale(mydata$`Highway mpg`)
mydata$price <- scale(mydata$Price)
#Checking dissimilarity
mydata$Dissimilarity_z = sqrt(mydata$`Wheel base`^2 + mydata$Horsepower^2 + mydata$`Peak rpm`^2 +
mydata$`Highway mpg`^2 + mydata$Price^2)
head(mydata[order(-mydata$Dissimilarity_z), c("ID", "Dissimilarity_z")],10)
## # A tibble: 10 × 2
## ID Dissimilarity_z
## <dbl> <dbl>
## 1 75 45623.
## 2 17 41667.
## 3 74 41207.
## 4 129 37496.
## 5 18 37274.
## 6 50 36347.
## 7 49 35867.
## 8 73 35377.
## 9 128 34536.
## 10 72 34513.
#Removing units with high dissimilarity
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
mydata <- mydata %>%
filter(!ID %in% c(75, 17, 74))
#Standardizing again after removing units
mydata$wheelbase <- scale(mydata$`Wheel base`)
mydata$horsepower <- scale(mydata$Horsepower)
mydata$peakrpm <- scale(mydata$`Peak rpm`)
mydata$highwaympg <- scale(mydata$`Highway mpg`)
mydata$price <- scale(mydata$Price)
round(head(mydata[c("Wheel base", "Horsepower", "Peak rpm", "Highway mpg", "Price")], 3), 2)
## # A tibble: 3 × 5
## `Wheel base` Horsepower `Peak rpm` `Highway mpg` Price
## <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 88.6 111 5000 27 13495
## 2 88.6 111 5000 27 16500
## 3 94.5 154 5000 26 16500
#Checking Euclidian distances
library(factoextra)
## Loading required package: ggplot2
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
Distance_euclidian <- get_dist(mydata[c("Wheel base", "Horsepower", "Peak rpm", "Highway mpg", "Price")],
method = "euclidian")
Distance_euclidian2 <- Distance_euclidian^2
fviz_dist(Distance_euclidian2)
#Calculating Hopkins statistic
get_clust_tendency(mydata[c("Wheel base", "Horsepower", "Peak rpm", "Highway mpg", "Price")],
n = nrow(mydata) - 1,
graph = FALSE)
## $hopkins_stat
## [1] 0.7304572
##
## $plot
## NULL
Hopkins statistic is above 0.5, which means that data has cluster tendency.
library(dplyr)
library(factoextra)
#Performing hierarchical clustering
WARD <- mydata[c("Wheel base", "Horsepower", "Peak rpm", "Highway mpg", "Price")] %>%
get_dist(method = "euclidean") %>%
hclust(method = "ward.D2")
WARD
##
## Call:
## hclust(d = ., method = "ward.D2")
##
## Cluster method : ward.D2
## Distance : euclidean
## Number of objects: 202
library(factoextra)
#Showing 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.
Based on dendrogram, I would cut the dendrogram into 3 or 5 groups.
fviz_dend(WARD,
k = 3,
cex = 0.1,
palette = "jama",
color_labels_by_k = TRUE,
rect = TRUE)
fviz_dend(WARD,
k = 5,
cex = 0.1,
palette = "jama",
color_labels_by_k = TRUE,
rect = TRUE)
#Classifying into 5 groups
mydata$ClassificationWARD <- cutree(WARD,
k = 5)
head(mydata[, c("ID", "ClassificationWARD")])
## # A tibble: 6 × 2
## ID ClassificationWARD
## <dbl> <int>
## 1 1 1
## 2 2 2
## 3 3 2
## 4 4 1
## 5 5 2
## 6 6 2
I decised to classify cars into 5 groups.
#Indicating initial leaders for K-means method
InitialLeaders <- aggregate(mydata[, c("wheelbase", "horsepower", "peakrpm", "highwaympg", "price")],
by = list(mydata$ClassificationWARD),
FUN = mean)
round(InitialLeaders, 3) #Averages of variables in each group
## Group.1 wheelbase horsepower peakrpm highwaympg price
## 1 1 0.231 0.059 -0.171 -0.414 -0.079
## 2 2 0.632 0.723 0.083 -0.754 0.572
## 3 3 1.198 0.557 -0.750 -0.840 1.515
## 4 4 0.772 2.340 0.182 -1.362 2.933
## 5 5 -0.541 -0.633 0.082 0.678 -0.698
#Implementing K-means method
library(factoextra)
K_MEANS <- hkmeans(mydata[c("wheelbase", "horsepower", "peakrpm", "highwaympg", "price")],
k = 5,
hc.metric = "euclidian",
hc.method = "ward.D2")
K_MEANS
## Hierarchical K-means clustering with 5 clusters of sizes 51, 24, 11, 82, 34
##
## Cluster means:
## wheelbase horsepower peakrpm highwaympg price
## 1 0.3838897 0.83962689 0.1553852 -0.8017781 0.4042925
## 2 1.5371275 -0.04376758 -1.4808336 -0.3924932 0.6768756
## 3 0.5740894 2.50569840 0.3476612 -1.4055535 2.9628964
## 4 -0.5361469 -0.79217712 -0.2243038 0.8616867 -0.7128176
## 5 -0.5535404 -0.12866787 1.2407059 -0.1437263 -0.3236691
##
## Clustering vector:
## [1] 5 5 1 5 1 1 1 1 1 1 5 5 2 2 2 3 3 4 4 4 4 4 5 4 4 4 5 4 1 4 5 4 5 5 5 5 5 5 5 5 5 5 4 4 4 4 3 3 3 4 4 4 4 4 5 5 5
## [58] 5 4 4 4 4 4 4 1 2 2 2 2 2 3 3 1 4 4 4 5 5 4 1 1 1 4 4 5 5 4 4 4 4 4 4 4 4 4 4 4 4 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2
## [115] 1 4 5 4 4 4 4 1 1 3 3 3 3 4 4 1 1 1 1 1 1 4 4 4 4 4 4 4 1 4 5 4 1 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 1 1 1 1 1 1 2
## [172] 2 2 2 2 1 1 1 1 4 4 4 4 4 4 5 5 5 1 4 5 1 1 1 1 1 1 1 1 1 2 1
##
## Within cluster sum of squares by cluster:
## [1] 80.16427 57.76122 57.33904 111.33243 46.90163
## (between_SS / total_SS = 64.8 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss" "betweenss" "size"
## [8] "iter" "ifault" "data" "hclust"
Final leaders and final classifications are shown. There have been reclassifications, all final leaders are different from initial ones.
There is also semi-high sum of squared between the groups (64.8), which means that there is variability between groups.
mydata$ClassificationK_MEANS <- K_MEANS$cluster
head(mydata[, c("ID", "ClassificationWARD", "ClassificationK_MEANS")])
## # A tibble: 6 × 3
## ID ClassificationWARD ClassificationK_MEANS
## <dbl> <int> <int>
## 1 1 1 5
## 2 2 2 5
## 3 3 2 1
## 4 4 1 5
## 5 5 2 1
## 6 6 2 1
#Showing initial and final groups (number of units in the groups)
table(mydata$ClassificationWARD)
##
## 1 2 3 4 5
## 34 41 11 12 104
table(mydata$ClassificationK_MEANS)
##
## 1 2 3 4 5
## 51 24 11 82 34
#Showing reclassifications
table(mydata$ClassificationWARD, mydata$ClassificationK_MEANS)
##
## 1 2 3 4 5
## 1 14 7 0 5 8
## 2 30 7 0 0 4
## 3 4 7 0 0 0
## 4 0 1 11 0 0
## 5 3 2 0 77 22
After K-means was performed, reclassifications happened.
Explanation of 1st row: Based on Ward’s classification, there were 34 units in group 1. After K-means, 14 units are still in group 1, while 7 units were reclassified to group 2, 5 units to group 4 and 8 to group 5.
Explanation of 3rd row: Based on Ward’s classification, there were 11 units in group 3. After K-means, 4 units were reclassified to group 1 and 7 units to group 2.
Explanation of 3rd column:: There are 11 units in group 3 after K-means classification. All 11 units were reclassified from group 4.
Explanation of 5th column:: There are 34 units in group 5 after K-means classification. 8 units were reclassified from group 1 and 4 from group 2, while 22 were already in group 5 .
#Group profiles
Averages <- K_MEANS$centers
round(Averages, 3)
## wheelbase horsepower peakrpm highwaympg price
## 1 0.384 0.840 0.155 -0.802 0.404
## 2 1.537 -0.044 -1.481 -0.392 0.677
## 3 0.574 2.506 0.348 -1.406 2.963
## 4 -0.536 -0.792 -0.224 0.862 -0.713
## 5 -0.554 -0.129 1.241 -0.144 -0.324
library(ggplot2)
library(tidyr)
Picture <- as.data.frame(Averages)
Picture$id <- 1:nrow(Picture)
Picture <- pivot_longer(Picture, cols = c("wheelbase", "horsepower", "peakrpm", "highwaympg", "price"))
Picture$Group <- factor(Picture$id,
levels = c(1, 2, 3, 4, 5),
labels = c("1", "2", "3", "4", "5"))
Picture$nameFactor <- factor(Picture$name,
levels = c("wheelbase", "horsepower", "peakrpm", "highwaympg", "price"),
labels = c("wheelbase", "horsepower", "peakrpm", "highwaympg", "price"))
#Showing ggplot
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")
Explanation of group 4:
Cluster 4 is the largest and presents 40.6% of total units. Cars in this group have below average wheel base, horsepower, peak rpm and price. The only variable above average is highway miles per gallon. Moreover, cars in this group have the lowest price and horsepower among all groups, while they have the highest average for miles per gallon.
Explanation of group 3:
The smallest group is cluster 3, which amounts for 5.45% of the total units, totaling 11 units. This group has above-average performance in four out of five variables. The only exception is highway mpg, which ranks as the lowest among all groups.
Cars in this group are the most expensive among all groups. What also stands out is that they also have the biggest horsepower among all groups. Additionally, both wheelbase and peak rpm slightly exceed the average, while highway mpg scores significantly below average and is the lowest among all groups.
#Checking the appropriateness of the cluster variables used
fit <- aov(cbind(`Wheel base`, Horsepower, `Peak rpm`, `Highway mpg`, Price) ~ as.factor(ClassificationK_MEANS),
data = mydata)
summary(fit)
## Response Wheel base :
## Df Sum Sq Mean Sq F value Pr(>F)
## as.factor(ClassificationK_MEANS) 4 3395.2 848.79 50.578 < 2.2e-16 ***
## Residuals 197 3306.0 16.78
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Response Horsepower :
## Df Sum Sq Mean Sq F value Pr(>F)
## as.factor(ClassificationK_MEANS) 4 234373 58593 176.17 < 2.2e-16 ***
## Residuals 197 65522 333
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Response Peak rpm :
## Df Sum Sq Mean Sq F value Pr(>F)
## as.factor(ClassificationK_MEANS) 4 25303247 6325812 61.546 < 2.2e-16 ***
## Residuals 197 20248052 102782
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Response Highway mpg :
## Df Sum Sq Mean Sq F value Pr(>F)
## as.factor(ClassificationK_MEANS) 4 5456.8 1364.20 72.664 < 2.2e-16 ***
## Residuals 197 3698.5 18.77
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Response Price :
## Df Sum Sq Mean Sq F value Pr(>F)
## as.factor(ClassificationK_MEANS) 4 8334432040 2083608010 199.01 < 2.2e-16 ***
## Residuals 197 2062589822 10469999
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
~ We assume normality and homoscedasticity are met.
H0: Mu(variable 1, G1) = Mu(variable 1, G2) = Mu(variable 1, G3) = Mu(variable 1, G4) = Mu(variable 1, G5)
H1: At least one Mu is different
We reject all H0 at p<0.001. Choice of cluster variables is correct.
Fuel type
#Checking validity with variables that were not used in the clustering process
chi_square <- chisq.test(mydata$`Fuel type`, as.factor(mydata$ClassificationK_MEANS))
## Warning in chisq.test(mydata$`Fuel type`, as.factor(mydata$ClassificationK_MEANS)): Chi-squared approximation may be
## incorrect
chi_square
##
## Pearson's Chi-squared test
##
## data: mydata$`Fuel type` and as.factor(mydata$ClassificationK_MEANS)
## X-squared = 53.811, df = 4, p-value = 5.766e-11
round(chi_square$res, 2)
##
## mydata$`Fuel type` 1 2 3 4 5
## gas 0.74 -2.07 0.35 0.01 0.61
## diesel -2.25 6.24 -1.04 -0.04 -1.83
round(chi_square$observed,2)
##
## mydata$`Fuel type` 1 2 3 4 5
## gas 51 12 11 74 34
## diesel 0 12 0 8 0
round(chi_square$expected,2)
##
## mydata$`Fuel type` 1 2 3 4 5
## gas 45.95 21.62 9.91 73.88 30.63
## diesel 5.05 2.38 1.09 8.12 3.37
Because more than 20% of expected frequencies are between 1 and 5, Pearson Chi-squared test is invalid and Fisher has to be used instead.
#Fisherman indep. test
Fisher <- fisher.test(mydata$`Fuel type`, as.factor(mydata$ClassificationK_MEANS))
Fisher
##
## Fisher's Exact Test for Count Data
##
## data: mydata$`Fuel type` and as.factor(mydata$ClassificationK_MEANS)
## p-value = 1.328e-08
## alternative hypothesis: two.sided
H0: There is no association between fuel type and classification.
H1: There is association.
BSD we reject H0 at p<0.001. There are statistical differences in fuel type between groups.
Engine location
chi_square <- chisq.test(mydata$`Engine location`, as.factor(mydata$ClassificationK_MEANS))
## Warning in chisq.test(mydata$`Engine location`, as.factor(mydata$ClassificationK_MEANS)): Chi-squared approximation may
## be incorrect
chi_square
##
## Pearson's Chi-squared test
##
## data: mydata$`Engine location` and as.factor(mydata$ClassificationK_MEANS)
## X-squared = 52.876, df = 4, p-value = 9.046e-11
round(chi_square$res, 2)
##
## mydata$`Engine location` 1 2 3 4 5
## rear -0.87 -0.60 7.02 -1.10 -0.71
## front 0.11 0.07 -0.86 0.14 0.09
round(chi_square$observed,2)
##
## mydata$`Engine location` 1 2 3 4 5
## rear 0 0 3 0 0
## front 51 24 8 82 34
round(chi_square$expected,2)
##
## mydata$`Engine location` 1 2 3 4 5
## rear 0.76 0.36 0.16 1.22 0.5
## front 50.24 23.64 10.84 80.78 33.5
addmargins(round(prop.table(chi_square$observed, 2), 3), 1)
##
## mydata$`Engine location` 1 2 3 4 5
## rear 0.000 0.000 0.273 0.000 0.000
## front 1.000 1.000 0.727 1.000 1.000
## Sum 1.000 1.000 1.000 1.000 1.000
Because more than 20% of frequencies are below 5, Pearson Chi-squared test is invalid and Fisher has to be used instead.
Fisher <- fisher.test(mydata$`Engine location`, as.factor(mydata$ClassificationK_MEANS))
Fisher
##
## Fisher's Exact Test for Count Data
##
## data: mydata$`Engine location` and as.factor(mydata$ClassificationK_MEANS)
## p-value = 0.0001219
## alternative hypothesis: two.sided
H0: There is no association between fuel type and classification.
H1: There is association.
BSD we reject H0 at p<0.001. There are statistical differences in engine location between groups.
202 cars were divided into 5 segments based on five standardized variables. For hierarchical clustering, I used Ward’s clustering algorithm and decided to divide them into 5 groups based on the analysis of the dendrogram. The classification was further optimized using K-Means clustering. After K-means, many reclassifications happened.
Based on ANOVA, all cluster variables are appropriate and they differentiate between one another in different groups. There is also association between classification and two categorical variables that were used for validation (engine location and fuel type).
Largest cluster is cluster 4, which consists of 82 units, while the smallest groups is cluster 3, which has only 11 units.