Reserach Question:

Is there a relationship between various environmental and socio-economic factors and the overall happiness score of cities worldwide?

#Source: https://www.kaggle.com/datasets/emirhanai/city-happiness-index-2024?resource=download

#Justification for PCA Method: Principal Component Analysis (PCA) was chosen as the method of analysis due to its ability to effectively reduce the dimensionality of the dataset while retaining as much information as possible. With numerous features such as decibel level, green space area, air quality index, cost of living index, healthcare index, and happiness score, PCA helps in identifying underlying patterns and relationships among these variables. By transforming the original variables into a smaller set of uncorrelated components, PCA allows for easier interpretation and visualization of the data, facilitating the identification of key factors influencing happiness scores in urban environments.

#importing data
mydata <- read_csv("~/Desktop/train.csv")
## Rows: 545 Columns: 10
## ── Column specification ────────────────────────────────────────────────────────────────────────────────────────────────
## Delimiter: ","
## chr (3): City, Month, Traffic_Density
## dbl (7): Year, Decibel_Level, Green_Space_Area, Air_Quality_Index, Happiness_Score, Cost_of_Living_Index, Healthcare...
## 
## ℹ 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.
#reviewing first 1o rows
head(mydata)
## # A tibble: 6 × 10
##   City        Month    Year Decibel_Level Traffic_Density Green_Space_Area Air_Quality_Index Happiness_Score
##   <chr>       <chr>   <dbl>         <dbl> <chr>                      <dbl>             <dbl>           <dbl>
## 1 New York    January  2024            70 High                          35                40             6.5
## 2 Los Angeles January  2024            65 Medium                        40                50             6.8
## 3 Chicago     January  2024            60 Medium                        30                55             7  
## 4 London      January  2024            55 High                          50                60             7.2
## 5 Paris       January  2024            60 High                          45                65             6.9
## 6 Berlin      January  2024            50 Low                           55                35             7.5
## # ℹ 2 more variables: Cost_of_Living_Index <dbl>, Healthcare_Index <dbl>

#The dataset consists of the following features:

City: Name of the city. Month: The month in which the data is recorded. Year: The year in which the data is recorded. Decibel_Level: Average noise levels in decibels, indicating the auditory comfort of the citizens. Traffic_Density: Level of traffic density (Low, Medium, High, Very High), which might impact citizens’ daily commute and stress levels. Green_Space_Area: Percentage of green spaces in the city, positively contributing to the mental well-being and relaxation of the inhabitants. Air_Quality_Index: Index measuring the quality of air, a crucial aspect affecting citizens’ health and overall satisfaction. Happiness_Score: The average happiness score of the city (on a 1-10 scale), representing the subjective well-being of the population. Cost_of_Living_Index: Index measuring the cost of living in the city (relative to a reference city), which could impact the financial satisfaction of the citizens. Healthcare_Index: Index measuring the quality of healthcare in the city, an essential component of the population’s well-being and contentment.

describe (mydata)
## mydata 
## 
##  10  Variables      545  Observations
## ------------------------------------------------------------------------------------------------------------------------
## City 
##        n  missing distinct 
##      545        0      227 
## 
## lowest : Adelaide        Amberley        Amsterdam       Aranga          Arrowtown      
## highest: Whangarei Heads Whangaruru      Whataroa        Whitianga       Yangon         
## ------------------------------------------------------------------------------------------------------------------------
## Month 
##        n  missing distinct 
##      545        0       12 
##                                                                                                               
## Value          April    August  December  February   January      July      June     March       May  November
## Frequency         45        45        42        52        44        45        46        56        43        40
## Proportion     0.083     0.083     0.077     0.095     0.081     0.083     0.084     0.103     0.079     0.073
##                               
## Value        October September
## Frequency         44        43
## Proportion     0.081     0.079
## ------------------------------------------------------------------------------------------------------------------------
## Year 
##        n  missing distinct     Info     Mean      Gmd 
##      545        0        6    0.967     2026    1.863 
##                                               
## Value       2024  2025  2026  2027  2028  2029
## Frequency    117   116   108    77    63    64
## Proportion 0.215 0.213 0.198 0.141 0.116 0.117
## 
## For the frequency table, variable is rounded to the nearest 0
## ------------------------------------------------------------------------------------------------------------------------
## Decibel_Level 
##        n  missing distinct     Info     Mean      Gmd 
##      545        0        9    0.885    56.78    6.391 
##                                                                 
## Value         50    55    60    65    70    75    80    85    90
## Frequency    124   245   127    10    10    13     9     5     2
## Proportion 0.228 0.450 0.233 0.018 0.018 0.024 0.017 0.009 0.004
## 
## For the frequency table, variable is rounded to the nearest 0
## ------------------------------------------------------------------------------------------------------------------------
## Traffic_Density 
##        n  missing distinct 
##      545        0        4 
##                                                   
## Value           High       Low    Medium Very High
## Frequency         26       370       129        20
## Proportion     0.048     0.679     0.237     0.037
## ------------------------------------------------------------------------------------------------------------------------
## Green_Space_Area 
##        n  missing distinct     Info     Mean      Gmd      .05      .10      .25      .50      .75      .90      .95 
##      545        0      485        1     1085    872.9       25       50      385     1065     1745     2153     2289 
## 
## lowest :    5   10   15   20   25, highest: 2405 2410 2415 2420 2425
## ------------------------------------------------------------------------------------------------------------------------
## Air_Quality_Index 
##        n  missing distinct     Info     Mean      Gmd      .05      .10      .25      .50      .75      .90      .95 
##      545        0       49    0.958    38.04    24.65       20       20       25       30       35       50      115 
## 
## lowest :   5  10  15  20  25, highest: 225 230 235 240 245
## ------------------------------------------------------------------------------------------------------------------------
## Happiness_Score 
##        n  missing distinct     Info     Mean      Gmd      .05      .10      .25      .50      .75      .90      .95 
##      545        0      458        1   -44.87    48.55  -114.74  -106.58   -82.10   -41.30    -0.50     6.96     7.90 
## 
## lowest : -122.9 -122.6 -122.3 -122   -121.7, highest: 8.2    8.3    8.4    8.5    8.6   
## ------------------------------------------------------------------------------------------------------------------------
## Cost_of_Living_Index 
##        n  missing distinct     Info     Mean      Gmd      .05      .10      .25      .50      .75      .90      .95 
##      545        0       23    0.852    30.46    15.91       20       20       20       25       25       60       85 
## 
## lowest :  20  25  30  35  40, highest: 110 115 120 125 130
## ------------------------------------------------------------------------------------------------------------------------
## Healthcare_Index 
##        n  missing distinct     Info     Mean      Gmd      .05      .10      .25      .50      .75      .90      .95 
##      545        0       24    0.959    93.09    7.207       66       85       95       96       97       98       98 
## 
## lowest : 35 40 45 50 55, highest: 95 96 97 98 99
## ------------------------------------------------------------------------------------------------------------------------

#Descriptive ststistics:

City: This categorical variable includes names of different cities, with 227 distinct cities represented in the dataset.

Month: This categorical variable indicates the month in which the data was recorded, with data spanning across 12 months.

Year: This variable denotes the year of data recording, ranging from 2024 to 2029.

Decibel_Level: This continuous variable represents the average noise levels in decibels, with values ranging from 50 to 90 and mean of 56.78

Traffic_Density: This categorical variable classifies traffic density into four categories: High, Low, Medium, and Very High.

Green_Space_Area: This continuous variable indicates the percentage of green spaces in each city, with values ranging from 5 to 2425 and mean of 1085

Air_Quality_Index: This continuous variable measures the air quality index in each city, with values ranging from 5 to 245 and mean of 38.04

Happiness_Score: This continuous variable represents the average happiness score of each city on a scale from -122.9 to 8.6 and mean of -44.87

Cost_of_Living_Index: This continuous variable measures the cost of living index relative to a reference city, with values ranging from 20 to 130 and mean of 30.46

Healthcare_Index: This continuous variable indicates the quality of healthcare in each city, with values ranging from 35 to 99 and mean of 93.09

#defining elements for correlation matrix
mydata_reg <- mydata [,c(-1,-2,-3,-5)] #excluding first three column and 5th, since it contains non-numeric data
str (mydata_reg)
## tibble [545 × 6] (S3: tbl_df/tbl/data.frame)
##  $ Decibel_Level       : num [1:545] 70 65 60 55 60 50 65 70 80 55 ...
##  $ Green_Space_Area    : num [1:545] 35 40 30 50 45 55 30 25 15 60 ...
##  $ Air_Quality_Index   : num [1:545] 40 50 55 60 65 35 70 75 80 30 ...
##  $ Happiness_Score     : num [1:545] 6.5 6.8 7 7.2 6.9 7.5 6 5.8 4.5 7.8 ...
##  $ Cost_of_Living_Index: num [1:545] 100 90 85 110 95 80 120 105 70 115 ...
##  $ Healthcare_Index    : num [1:545] 80 75 70 85 80 85 90 75 60 88 ...
fit <- lm(Happiness_Score ~ Decibel_Level + Green_Space_Area + Air_Quality_Index + Cost_of_Living_Index + Healthcare_Index, 
          data = mydata_reg)
library(car)
vif(fit)  
##        Decibel_Level     Green_Space_Area    Air_Quality_Index Cost_of_Living_Index     Healthcare_Index 
##             4.018849             1.507556            10.272982             1.467070            10.493624
mean(vif(fit)) #detecting multicollinearity
## [1] 5.552016

We can see high correlations between variables (VIF for variables Air_Quality_Index and Healthcare_Index are above 5, also average vif is above 5, which is way to high). Hence we will join the variables into 2 components.

mydata_PCA <- mydata[, c("Green_Space_Area", "Decibel_Level", "Cost_of_Living_Index", "Air_Quality_Index")] 
# correlation matrix
R <- cor(mydata_PCA) 
round(R, 3)
##                      Green_Space_Area Decibel_Level Cost_of_Living_Index Air_Quality_Index
## Green_Space_Area                1.000        -0.368               -0.516            -0.409
## Decibel_Level                  -0.368         1.000                0.342             0.858
## Cost_of_Living_Index           -0.516         0.342                1.000             0.350
## Air_Quality_Index              -0.409         0.858                0.350             1.000
library(psych)
## 
## Attaching package: 'psych'
## The following object is masked from 'package:car':
## 
##     logit
## The following object is masked from 'package:Hmisc':
## 
##     describe
## The following objects are masked from 'package:ggplot2':
## 
##     %+%, alpha
corPlot(R)

The correlations between all variables are above 0.3 except between variables decibel level and green space area, where we see see moderate negative correlation is -0.37.

#H0:Correlation coefficients are equal to 0
#H1:At least some correlation coefficients are not equal to 0
cortest.bartlett(R, 
                 n = nrow(mydata_PCA))
## $chisq
## [1] 1008.697
## 
## $p.value
## [1] 1.17614e-214
## 
## $df
## [1] 6

We reject null hypothesis at p value less than 0.05. At least some correlation coefficient are not equal to 0

#measuring sample adequacy for each variable
library(psych)
KMO(R)
## Kaiser-Meyer-Olkin factor adequacy
## Call: KMO(r = R)
## Overall MSA =  0.63
## MSA for each item = 
##     Green_Space_Area        Decibel_Level Cost_of_Living_Index    Air_Quality_Index 
##                 0.73                 0.59                 0.72                 0.59

MSA of 0.63 suggests mediocre sampling adequacy. Some variables such as Green_Space_Area and Cost_of_Living_Index show relatively high adequacy (0.73 (middling) and 0.72 (middling), respectively), others like Decibel_Level, Air_Quality_Index exhibit acceptable adequacy (0.59, 0.59 respectively). However the KMO measure is useful for assessing the suitability of data for factor analysis, it is not mandatory for PCA.

#performing PCA
library(FactoMineR) 
components <- PCA(mydata_PCA, 
                  scale.unit = TRUE, #to standardize data
                  graph = FALSE)
library(factoextra) 
get_eigenvalue(components)
##       eigenvalue variance.percent cumulative.variance.percent
## Dim.1  2.4411675        61.029186                    61.02919
## Dim.2  0.9350423        23.376057                    84.40524
## Dim.3  0.4827466        12.068665                    96.47391
## Dim.4  0.1410436         3.526091                   100.00000

If we take only PC 1 (61.60%) we will lose to much info, so we will take first two to catch 84.40% Eigenvalues in first two components >1 (Kaiser’s rule)

fviz_eig(components,
         choice = "eigenvalue",
         main = "Screeplot",
         ylab = "Eigenvalues",
         xlab = "Principal Component",
         addlabels = TRUE)

Based on Elbow method biggest break between second (1.4) and third (0.6). Two components should be retained.

#parellel analysis to find out number of components to retain
fa.parallel(mydata_PCA, 
            sim = FALSE, 
            fa = "pc")

## Parallel analysis suggests that the number of factors =  NA  and the number of components =  1

Parallel analysis suggests that the number of factors = NA and the number of components = 2 (first two) The actual eigenvalue exceeds the expected eigenvalue. Kaiser’s guideline suggests that the eigenvalues of the selected components ought to surpass the average variance of the original variables. Therefore, we should consider components with eigenvalues greater than 1, which, in this scenario, are the first two components.

components <- PCA(mydata_PCA, 
                  scale.unit = TRUE, #standardized measured variables
                  graph = FALSE,
                  ncp = 2) #optimal number of components
components
## **Results for the Principal Component Analysis (PCA)**
## The analysis was performed on 545 individuals, described by 4 variables
## *The results are available in the following objects:
## 
##    name               description                          
## 1  "$eig"             "eigenvalues"                        
## 2  "$var"             "results for the variables"          
## 3  "$var$coord"       "coord. for the variables"           
## 4  "$var$cor"         "correlations variables - dimensions"
## 5  "$var$cos2"        "cos2 for the variables"             
## 6  "$var$contrib"     "contributions of the variables"     
## 7  "$ind"             "results for the individuals"        
## 8  "$ind$coord"       "coord. for the individuals"         
## 9  "$ind$cos2"        "cos2 for the individuals"           
## 10 "$ind$contrib"     "contributions of the individuals"   
## 11 "$call"            "summary statistics"                 
## 12 "$call$centre"     "mean of the variables"              
## 13 "$call$ecart.type" "standard error of the variables"    
## 14 "$call$row.w"      "weights for the individuals"        
## 15 "$call$col.w"      "weights for the variables"
print(components$var$cor)
##                           Dim.1      Dim.2
## Green_Space_Area     -0.7057232  0.4952531
## Decibel_Level         0.8575796  0.4398535
## Cost_of_Living_Index  0.6677703 -0.5744621
## Air_Quality_Index     0.8727899  0.4077853

Decibel_Level: Proportion of info that was transformed from PC1 and PC2 is 73.01%, we lost 26.99% of information Correlation between PC1 and Air_Quality_Index and Decibel_Level are positive and strong (Air_Quality_Index), semi strong (Decibel_Level)

print (components$var$contrib)
##                         Dim.1    Dim.2
## Green_Space_Area     20.40193 26.23150
## Decibel_Level        30.12668 20.69116
## Cost_of_Living_Index 18.26655 35.29324
## Air_Quality_Index    31.20483 17.78410

Decibel_Level contributed the most information in forming PC1/Dimension 1 (30.12%), Cost of Living index the least information (18.26%).Air_Quality_Index contributed 17.78% to PC2

fviz_pca_var(components, 
             repel = TRUE)

PC1 measures General enviromental factors - PC2 measures contrast between enviromental factors (Green Space Area, Decibel Level, Air Quality Index) and socio-economic factor (Cost of Living)

library(factoextra)
fviz_pca_biplot(components) 

Unit 70 (Ho Chi Minh City): is above average environmental factors and better in socio-economic factors Unit 34 (OSlo): is above average in general socio -economic factors and better in environmental factors Unit 88 (Napier): is below average in general environmental factors factors and better in socio -economic factors

head(components$ind$coord)
##      Dim.1     Dim.2
## 1 3.127932 -1.772033
## 2 2.675425 -1.702336
## 3 2.256319 -1.841964
## 4 2.428038 -2.807431
## 5 2.604301 -1.997579
## 6 1.030610 -2.580606
components$ind$coord[24,]
##     Dim.1     Dim.2 
##  2.028820 -2.191845
mydata_PCA_std <- as.data.frame (scale(mydata_PCA))
mydata_PCA[24,] #standartized values for ID 24
## # A tibble: 1 × 4
##   Green_Space_Area Decibel_Level Cost_of_Living_Index Air_Quality_Index
##              <dbl>         <dbl>                <dbl>             <dbl>
## 1               65            60                   90                35

Unit 24 is Barcelona is above average in Decibel Level and Cost of Living Index

mydata$PC1 <- components$ind$coord[,1]
mydata$PC2 <- components$ind$coord[,2]
head(mydata,3)
## # A tibble: 3 × 12
##   City        Month    Year Decibel_Level Traffic_Density Green_Space_Area Air_Quality_Index Happiness_Score
##   <chr>       <chr>   <dbl>         <dbl> <chr>                      <dbl>             <dbl>           <dbl>
## 1 New York    January  2024            70 High                          35                40             6.5
## 2 Los Angeles January  2024            65 Medium                        40                50             6.8
## 3 Chicago     January  2024            60 Medium                        30                55             7  
## # ℹ 4 more variables: Cost_of_Living_Index <dbl>, Healthcare_Index <dbl>, PC1 <dbl>, PC2 <dbl>

Multicollinearity cannot occur because the principal components (PC1 and PC2) are orthogonal and independent.

cor (x=mydata$PC1, y=mydata$PC2)
## [1] 5.251783e-16

No correlation observed between PC1 and PC2

mydata$Traffic_Density_F <- factor(mydata$Traffic_Density,
                             levels =c("High", "Medium", "Low", "Very High") ,
                             labels = c(1,2,3,4))
fit1 <- lm(Happiness_Score ~ PC1 + PC2 + Traffic_Density_F,
          data = mydata)
vif(fit1) 
##                       GVIF Df GVIF^(1/(2*Df))
## PC1               6.118725  1        2.473606
## PC2               2.060995  1        1.435617
## Traffic_Density_F 7.873966  3        1.410476
mean(vif(fit1))
## [1] 2.930376
#H0: Errors normaly distributed
#H1: Errors are not normaly distributed
mydata$StdResid <- rstandard(fit1)
mydata$StdFitted <- scale(fit1$fitted.values)

hist(mydata$StdResid, 
     xlab = "Standardized residuals", 
     ylab = "Frequency", 
     main = "Histrogram of standardized residuals")

#Ho: Errors are normally distributed
#Ha: Errors are not normally distributed

shapiro.test(mydata$StdResid)
## 
##  Shapiro-Wilk normality test
## 
## data:  mydata$StdResid
## W = 0.97384, p-value = 2.736e-08

Based on p valeu less than 0.05 I have enough evidence to reject the null hypothesis. This suggests that the distribution of standardized residuals significantly deviates from normality

#check for linearity and homoskedasticity
library(ggplot2)
ggplot(mydata, aes(y=StdResid, x=StdFitted)) +
  theme_dark() +
  geom_point(colour = "snow") +
  ylab("Standardized residuals") +
  xlab("Standardized fitted values")

library(olsrr)
## 
## Attaching package: 'olsrr'
## The following object is masked from 'package:datasets':
## 
##     rivers
ols_test_breusch_pagan(fit1)
## 
##  Breusch Pagan Test for Heteroskedasticity
##  -----------------------------------------
##  Ho: the variance is constant            
##  Ha: the variance is not constant        
## 
##                    Data                     
##  -------------------------------------------
##  Response : Happiness_Score 
##  Variables: fitted values of Happiness_Score 
## 
##          Test Summary           
##  -------------------------------
##  DF            =    1 
##  Chi2          =    99.03685 
##  Prob > Chi2   =    2.478467e-23

Based on the p value less than 0.05, we would reject the null hypothesis and conclude that there is evidence of heteroskedasticity

mydata$ID <- seq.int(nrow(mydata))
head(mydata[order(mydata$StdResid), c("ID", "StdResid") ], 3) #identifying outliers
## # A tibble: 3 × 2
##      ID StdResid
##   <int>    <dbl>
## 1    22    -3.25
## 2    26    -2.87
## 3    10    -2.82
library(dplyr)
mydata <- mydata %>%
  filter(!ID %in% c(22, 26,10)) #removing outliers
fit2 <- lm(Happiness_Score ~ PC1 + PC2 + Traffic_Density_F,
          data = mydata)
summary (fit2)
## 
## Call:
## lm(formula = Happiness_Score ~ PC1 + PC2 + Traffic_Density_F, 
##     data = mydata)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -70.910 -17.371   1.643  18.553  39.112 
## 
## Coefficients:
##                    Estimate Std. Error t value Pr(>|t|)    
## (Intercept)         -85.602      7.198 -11.892  < 2e-16 ***
## PC1                  23.652      1.612  14.669  < 2e-16 ***
## PC2                 -21.694      1.473 -14.731  < 2e-16 ***
## Traffic_Density_F2   42.906      7.076   6.064 2.51e-09 ***
## Traffic_Density_F3   45.014      8.216   5.479 6.60e-08 ***
## Traffic_Density_F4   11.986      8.418   1.424    0.155    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 22.94 on 536 degrees of freedom
## Multiple R-squared:  0.7093, Adjusted R-squared:  0.7066 
## F-statistic: 261.5 on 5 and 536 DF,  p-value: < 2.2e-16

Data doesn’t support that Very High traffic density effects Happiness score (p value more than 0.05), however Medium and Low traffic density contributes to happiness score on average by 42 and 45 points respectivily

If value PC1 increases by 1 standart deviation, the number of score hapiness on average increases by 23 points (p value less than o.05), assuming all other variables remain constant

If value of PC 2 increases, happiness score will decrease by 21 points.

#Conclusion:

Principal component analysis was performed on 4 standardized variables (n = 545). The KMO measure confirms the appropriateness of the variables, KMO = 0.63, the data falls into the category “Mediocre”. The MSA statistics for the individual variables are above 0.50 for four variables. Based on the parallel analysis (and other rules as well), it makes most sense to retain the first two principal components, which together summarize almost 84.40% of the information in the original 4 variables.Based on the component’s loadings, we conclude that PC1 (lamda 1 = 3.12) represents students’ general abilities, while PC2 (lamda2=2.67) represents the contrast between environmental and socio-economic factors