R语言pca(Principal)

data <- data.frame(
          x1 = c(148,139,160,149,159,142,153,150,151,139,140
                 ,161,158,140,137,152,149,145,160,156,151,147,
                 157,147,157,151,144,141,139,148),
          x2 = c(41,34,49,36,45,31,43,43,42,31,29,47,49,33,31
                 ,35,47,35,47,44,42,38,39,30,48,36,36,30,32,38),
          x3 = c(72,71,77,67,80,66,76,77,77,68,64,78,78,67,66,
                 73,82,70,74,78,73,73,68,65,80,74,68,67,68,70),
          x4 = c(78,76,86,79,86,76,83,79,80,74,74,84,83,77,73,
                 79,79,77,87,85,82,78,80,75,88,80,76,76,73,78)
          )
#1、先得到样本的相关系数矩阵
r <- cor(data)
r
       x1        x2        x3        x4

x1 1.0000000 0.8631621 0.7321119 0.9204624
x2 0.8631621 1.0000000 0.8965058 0.8827313
x3 0.7321119 0.8965058 1.0000000 0.7828827
x4 0.9204624 0.8827313 0.7828827 1.0000000

#2、样本矩阵的标准化,这里采用均值标准化
head(scale(data))
          x1         x2          x3          x4

[1,] -0.1366952 0.3560249 -0.04530114 -0.31999814
[2,] -1.3669516 -0.7275291 -0.23944887 -0.78828809
[3,] 1.5036468 1.5943722 0.92543751 1.55316168
[4,] 0.0000000 -0.4179422 -1.01603978 -0.08585316
[5,] 1.3669516 0.9751985 1.50788070 1.55316168
[6,] -0.9568661 -1.1919093 -1.21018751 -0.78828809

#3、计算r的特征值,求出特征值矩阵
library(psych)

Warning: package ‘psych’ was built under R version 3.6.3
pca <- principal(data,nfactors = 1,rotate = “varimax”)

pca

Principal Components Analysis
Call: principal(r = data, nfactors = 1, rotate = “varimax”)
Standardized loadings (pattern matrix) based upon correlation matrix
PC1 h2 u2 com
x1 0.94 0.87 0.125 1
x2 0.97 0.94 0.062 1
x3 0.90 0.82 0.181 1
x4 0.95 0.91 0.090 1

             PC1

SS loadings 3.54
Proportion Var 0.89

Mean item complexity = 1
Test of the hypothesis that 1 component is sufficient.
The root mean square of the residuals (RMSR) is 0.06
with the empirical chi square 1.45 with prob < 0.48
Fit based upon off diagonal values = 0.99

pca$values # 特征值=sdev^2

[1] 3.54109800 0.31338316 0.07940895 0.06610989

pca$loadings #载荷,不是特征向量

Loadings:
PC1
x1 0.935
x2 0.968
x3 0.905
x4 0.954
PC1
SS loadings 3.541
Proportion Var 0.885

#此处score=prcomp的score/sdev
pca$scores[1:5,] #此处为因子得分,不是主成分得分

[1] -0.03652629 -0.83349270 1.48798632 -0.39706882 1.43142072

#此处为上面loadings/特征值,也称成份得分系数或者因子系数

pca$weights 

PC1
x1 0.2640935
x2 0.2734487
x3 0.2555562
x4 0.2693877

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值