######################
library(magrittr)
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
library(GGally)
## Warning: package 'GGally' was built under R version 4.2.3
## Loading required package: ggplot2
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
#read data
tt <- read.table("shell.txt", header = TRUE)
head(tt)
##   length width height
## 1     98    81     38
## 2    103    84     38
## 3    103    86     42
## 4    105    86     42
## 5    109    88     44
## 6    123    92     50
str(tt)
## 'data.frame':    24 obs. of  3 variables:
##  $ length: int  98 103 103 105 109 123 123 133 133 133 ...
##  $ width : int  81 84 86 86 88 92 95 99 102 102 ...
##  $ height: int  38 38 42 42 44 50 46 51 51 51 ...
tt %>% select(length, width, height) %>% ggpairs(upper = list(continuous = "points"), lower = list(continuous = "cor"))

#Phân tích PCA
pca <- prcomp(tt, scale = TRUE)
print(pca)
## Standard deviations (1, .., p=3):
## [1] 1.7145842 0.1853043 0.1608205
## 
## Rotation (n x k) = (3 x 3):
##              PC1        PC2        PC3
## length 0.5781417 -0.1373949 -0.8042853
## width  0.5771970 -0.6278484  0.5221591
## height 0.5767112  0.7661129  0.2836814
summary(pca)
## Importance of components:
##                           PC1     PC2     PC3
## Standard deviation     1.7146 0.18530 0.16082
## Proportion of Variance 0.9799 0.01145 0.00862
## Cumulative Proportion  0.9799 0.99138 1.00000
#pc1 giải thích 97.99 % phương sai:
#vẽ biểu đồ  bằng hàm fviz_eig() trong thư viện factoextra
library(factoextra)
## Warning: package 'factoextra' was built under R version 4.2.3
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
fviz_eig(pca)

#Như vậy PC1 giải thích gần 100% phương sai
fviz_pca_ind(pca, col.ind = "cos2", gradient.cols = c("red","blue", "green1"), repel = TRUE)

#Như vậy component 1 giải thích 98%, component 2 giải thích 1.1 %. 

#biểu đồ 3:
fviz_pca_var(pca, col.var = "contrib", gradient.cols = c("red", "blue", "black"), repel = TRUE)

#Phần trăm của contribution của mỗi một component

#Tóm lại PCA giúp cho 3 biến giảm 1 biến, có thể giải thích được % phương sai, giúp cho phát hiện ngoại vi hiệu quả.


######################