Data set is from Kaggle: https://www.kaggle.com/datasets/vipulgohel/clustering-pca-assignment

RQ: I got a task to analyze the data of country economic and life performance with a lot of variables. Due to high multicolineriaty in data set I decided to use principal component analysis to reduce dimmensionalty and simplfy the data without losing much information.

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 <- read.table("/home/mohor/Desktop/MVA/HW1/Country-data.csv", header=TRUE, sep=",", dec=".")
## Warning in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,
## : EOF within quoted string
## Warning in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,
## : number of items read is not a multiple of the number of columns
#mydata <- mydata[ c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)]
head(mydata)
##               country child_mort exports health imports income inflation
## 1         Afghanistan       90.2    10.0   7.58    44.9   1610      9.44
## 2             Albania       16.6    28.0   6.55    48.6   9930      4.49
## 3             Algeria       27.3    38.4   4.17    31.4  12900     16.10
## 4              Angola      119.0    62.3   2.85    42.9   5900     22.40
## 5 Antigua and Barbuda       10.3    45.5   6.03    58.9  19100      1.44
## 6           Argentina       14.5    18.9   8.10    16.0  18700     20.90
##   life_expec total_fer  gdpp
## 1       56.2      5.82   553
## 2       76.3      1.65  4090
## 3       76.5      2.89  4460
## 4       60.1      6.16  3530
## 5       76.8      2.13 12200
## 6       75.8      2.37 10300

Descriptions
country - Name of the country,
child_mort - Death of children under five years of age per 1000 live births,
exports - Exports of goods and services; Exports of goods and services given as %age of the Total GDP;
imports - Imports of goods and services, Given as %age of the Total GDP;
income - Net income per person;
inflation - The measurement of the annual growth rate of the Total GDP;
life_expactancy - The average number of years a newborn child would live if the current mortality patterns are to remain the same;
total_fer - The number of children born to each woman if the current age-fertility rates remain the same.

#checking if there are any missing values in the dataset  
any_na <- any(is.na(mydata)) 
if (any_na) {
  na_values <- which(is.na(mydata), arr.ind = TRUE)
}
# Removing rows with NA values
mydata <- na.omit(mydata)
any_na <- any(is.na(mydata)) 
print(any_na)
## [1] FALSE
mydata <- mydata[, c(3, 4, 6, 8, 10)]
head(mydata)
##   exports health income life_expec  gdpp
## 1    10.0   7.58   1610       56.2   553
## 2    28.0   6.55   9930       76.3  4090
## 3    38.4   4.17  12900       76.5  4460
## 4    62.3   2.85   5900       60.1  3530
## 5    45.5   6.03  19100       76.8 12200
## 6    18.9   8.10  18700       75.8 10300
library(psych)
summary(mydata)
##     exports          health           income        life_expec   
##  Min.   : 8.92   Min.   : 2.460   Min.   :  609   Min.   :47.50  
##  1st Qu.:20.55   1st Qu.: 4.525   1st Qu.: 2625   1st Qu.:61.45  
##  Median :35.90   Median : 5.955   Median : 9825   Median :72.90  
##  Mean   :36.88   Mean   : 6.572   Mean   :14655   Mean   :70.03  
##  3rd Qu.:50.48   3rd Qu.: 8.002   3rd Qu.:16825   3rd Qu.:76.55  
##  Max.   :85.10   Max.   :11.600   Max.   :80600   Max.   :82.00  
##       gdpp      
##  Min.   :  231  
##  1st Qu.: 1207  
##  Median : 4510  
##  Mean   :10579  
##  3rd Qu.:11450  
##  Max.   :51900

Descriptive statistics
- The largest exports in % for a country in data set is 85,10.
- More than 50% of countires had inflation higher than 6.48%.
- Average life excaptancy in data set is 70,03 years.

mydata_PCA <- mydata
R <- cor(mydata_PCA)
round(R, 3)
##            exports health income life_expec  gdpp
## exports      1.000 -0.219  0.411      0.177 0.255
## health      -0.219  1.000  0.214      0.345 0.454
## income       0.411  0.214  1.000      0.599 0.858
## life_expec   0.177  0.345  0.599      1.000 0.602
## gdpp         0.255  0.454  0.858      0.602 1.000
corPlot(R)

I draw a correlation matrix to check the correlations between variables. Rule is that there must ber sufficiently high correlation(above 0.3). I removed the variables with low correlation, but still some of them are low. But due to academic reasseons I will say it OK and continue with analysis.

cortest.bartlett(R, n = nrow(mydata_PCA))
## $chisq
## [1] 93.61602
## 
## $p.value
## [1] 1.024478e-15
## 
## $df
## [1] 10

h0: P = I
h1: P != I
BSD we can reject H0 and conclude that at least one correlation differ from 0(p<0.001).

det(R)
## [1] 0.07693284

It is not important for PCA(we check it only for FA).

KMO(R)
## Kaiser-Meyer-Olkin factor adequacy
## Call: KMO(r = R)
## Overall MSA =  0.64
## MSA for each item = 
##    exports     health     income life_expec       gdpp 
##       0.67       0.49       0.60       0.89       0.61

We can see that KMO and individual MSA are bigger than 0.5. So in this way we are good. KMO is 0,64 (above 0,5). Individual MSA should be above 0,5 as well. Health is not, but for PCA this rule is not that strict and we don’t need to remove health as variable.

Summary: Is data suitable?
- Bartlett test of specificity shows that data is OK
- we have sufficiently high correlation
- KMO(and MSA) both higher than 0.5

So we can continue with the analysis and find out how many components we need.

library(FactoMineR)
components <- PCA(mydata_PCA,
                  scale.unit = TRUE,
                  graph = FALSE
                  )

library(factoextra)
## Loading required package: ggplot2
## 
## Attaching package: 'ggplot2'
## The following objects are masked from 'package:psych':
## 
##     %+%, alpha
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
get_eigenvalue(components)
##       eigenvalue variance.percent cumulative.variance.percent
## Dim.1  2.6875397        53.750795                    53.75079
## Dim.2  1.2652589        25.305178                    79.05597
## Dim.3  0.5053034        10.106069                    89.16204
## Dim.4  0.4401808         8.803616                    97.96566
## Dim.5  0.1017171         2.034343                   100.00000

2.69 / 5 = 53,8% PC1 have 53,8% of total information.
Variance of PC1 is 2,69.
I we will chose to use 2 principal components, we will simplify data from 5 to 2 variables and lose 21% of information.

Kaiser rule
Based on Kaiser rule we should take first two PCs, because they have eigenvalues above 1.

Diagram of eigenvalues

library(factoextra)
fviz_eig(components,
         choice = "eigenvalue",
         main = "Scree plot",
         ylab = "Eigenvalue",
         xlab = "Principal component",
         addlabels = TRUE)

We can see that the biggest change of slope is at component 3. So we have take one less -> 2 components.

Parallel analysis
Is the most important rule for choosing number of components.

library(psych)
fa.parallel(mydata_PCA, 
            sim = FALSE, 
            fa = "pc",
            ) 

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

RULE: empirical eigenvalues > theoretical eigenvalues
Also this rule shows that we have to take 2 PCs.

Summary: How many components?
- parallel analysis(the most important rule) -> 2
- eigenvalues > 1 -> 2
- scree plot slope -> 2

So we can conclude that optimal number of PCs for our data is 2.

library(FactoMineR)
components <- PCA(mydata_PCA, 
                  scale.unit = TRUE, 
                  graph = FALSE,
                  ncp = 2) 

components
## **Results for the Principal Component Analysis (PCA)**
## The analysis was performed on 40 individuals, described by 5 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
## exports    0.3822451  0.80763068
## health     0.4773584 -0.74485146
## income     0.9074054  0.20782944
## life_expec 0.7913366 -0.10489031
## gdpp       0.9294941 -0.06318893

We can see that DIM1 represents general performance of the country, and DIM2 represents contrast between economy and health(life).
Linear relationship between gdpp and PC1 is positive and very strong. (0,38)on2 + (0.8)on2 = 78,4%
78.4% of information was transferred from exports to both principal components. We lost 21,6% of information from exports.

print(components$var$contrib) 
##                Dim.1      Dim.2
## exports     5.436619 51.5520821
## health      8.478798 43.8490258
## income     30.637110  3.4137736
## life_expec 23.300630  0.8695435
## gdpp       32.146844  0.3155750

5.44 % - The amount of information contributed to PC1 by exports. 51.55%- The amount of information contributed to PC2 by exports.

library(factoextra)
fviz_pca_var(components, 
             repel = TRUE)

DIM1 - General performance of the country.
DIM2 - Contrast - between health and economy.

library(factoextra)
fviz_pca_biplot(components) 

ID 12: Above average in general performance and is better in economic factors than in health(life exp).
ID 4: Bellow average in general performance and is better in economic factors than in health(life exp).
ID 32: Is the lowest in general performance and equaly good in economic and health factors.

head(components$ind$coord)
##        Dim.1      Dim.2
## 1 -1.8114148 -1.2433731
## 2 -0.1835906 -0.4252155
## 3 -0.2024221  0.6202578
## 4 -1.2347888  1.9673097
## 5  0.6305766  0.4403036
## 6  0.3982221 -1.0936281
components$ind$coord[8, ]
##     Dim.1     Dim.2 
##  3.231161 -1.193729
mydata_PCA_std <- scale(mydata_PCA) 
mydata_PCA_std[8, ] 
##    exports     health     income life_expec       gdpp 
## -0.8887256  0.8407189  1.6256479  1.3434014  2.8301684

We can see that unit ID8 is bellow average in exports and above average in health, income, life expectancy and gdpp.

mydata$PC1 <- components$ind$coord[ , 1] 
mydata$PC2 <- components$ind$coord[ , 2] 

head(mydata)
##   exports health income life_expec  gdpp        PC1        PC2
## 1    10.0   7.58   1610       56.2   553 -1.8114148 -1.2433731
## 2    28.0   6.55   9930       76.3  4090 -0.1835906 -0.4252155
## 3    38.4   4.17  12900       76.5  4460 -0.2024221  0.6202578
## 4    62.3   2.85   5900       60.1  3530 -1.2347888  1.9673097
## 5    45.5   6.03  19100       76.8 12200  0.6305766  0.4403036
## 6    18.9   8.10  18700       75.8 10300  0.3982221 -1.0936281
cor(x=mydata$PC1, y=mydata$PC2)
## [1] 3.118227e-16

Conclusion
We managed to reduce dimmensionalty of our data by reducing number of variables without losing much information. We managed to reduce number of variables from 5 to 2 and with this simplification still manage to explain 78% of variability(inforamtion) of initiall 5 variables. Those principal components would know be suitable to use them in regression function and we won’t have problem with multicolinearity, because they are orthogonal(correlation between PC1 and PC2 is practically 0).