######################
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.4.1     ✔ purrr   1.0.1
## ✔ tibble  3.1.8     ✔ dplyr   1.1.0
## ✔ tidyr   1.3.0     ✔ stringr 1.5.0
## ✔ readr   2.1.4     ✔ forcats 1.0.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
d <- read.csv('Body composition short data 400.csv')
head(d)
##   id age sex heright weight   bmi  fatmass leanmass pcfat
## 1  1  67   0   156.0   45.0 18.49 16.49388 27.97842 37.09
## 2  5  46   0   154.6   70.0 29.29 31.67295 39.43190 44.54
## 3  7  47   0   144.0   50.0 24.11 21.82686 29.10873 42.85
## 4 13  50   1   160.0   64.0 25.00 26.67193 46.57254 36.41
## 5 21  47   0   158.2   51.5 20.58 20.65137 31.72096 39.43
## 6 42  66   0   158.0   55.0 22.03 22.60782 32.89753 40.73
dat <- d %>% select(id, fatmass, bmi)
head(dat)
##   id  fatmass   bmi
## 1  1 16.49388 18.49
## 2  5 31.67295 29.29
## 3  7 21.82686 24.11
## 4 13 26.67193 25.00
## 5 21 20.65137 20.58
## 6 42 22.60782 22.03
#visual tương quan
ggplot(dat, aes(bmi, fatmass))+geom_point()

pca <- princomp(~bmi+fatmass, data=dat)
#princomp có sẵn trong base R
summary(pca)
## Importance of components:
##                           Comp.1     Comp.2
## Standard deviation     5.9569960 1.60781697
## Proportion of Variance 0.9320983 0.06790165
## Cumulative Proportion  0.9320983 1.00000000
#Như vậy comp.1 giải thích 93 % không cần comp.2
loadings(pca)
## 
## Loadings:
##         Comp.1 Comp.2
## bmi      0.438  0.899
## fatmass  0.899 -0.438
## 
##                Comp.1 Comp.2
## SS loadings       1.0    1.0
## Proportion Var    0.5    0.5
## Cumulative Var    0.5    1.0
#Biếr hệ số hồi quy và trọng số
#PC1 = 0.438 x bmi + 0.899 x fatmass
#PC2 = 0.899 x bmi - 0.438 x fatmass
#biến tiềm ẩn pc1 giải thích 50%m comp.2 thêm 50%
head(pca$scores)
##       Comp.1     Comp.2
## 1 -6.5834686 -2.0816066
## 2 11.7922166  0.9808042
## 3  0.6720240  0.6355432
## 4  5.4175783 -0.6860155
## 5 -1.9305752 -2.0232449
## 6  0.4632779 -1.5764070
#biết bao nhiêu giá trị comp.1 và comp.2
var(pca$scores)
##              Comp.1       Comp.2
## Comp.1 3.557474e+01 1.694412e-15
## Comp.2 1.694412e-15 2.591554e+00
######################