【R语言】R主成分分析(Principal Component Analysis, PCA)

拇指科研 2018-06-21 10:16:20

主成分分析是一种统计方法,人们在研究多变量的课题时,变量个数太多就会增加课题的复杂性。人们自然希望变量个数较少而得到的信息较多。主成分分析是对于原先提出的所有变量,将重复的变量(关系紧密的变量)删去多余,建立尽可能少的新变量,使得这些新变量是两两不相关的,而且这些新变量在反映课题的信息方面尽可能保持原有的信息

?

R软件提供两个不同的功能来实现主成分分析。这两个功能分别是princomp和prcomp。

?

下面以iris数据为例介绍两个功能的使用:

?

> myiris <- iris[,-5]

?

> pca1 <-princomp(myiris)

?

> pca2 <- prcomp(myiris)

?

> pca1

?

Call:

?

princomp(x = myiris)

?

Standard deviations:

?

?Comp.1???Comp.2??? Comp.3?? Comp.4

?

2.0494032 0.49097140.27872590.1538707

?

4? variablesand?150 observations.

?

> pca2

?

Standard deviations:

?

[1] 2.05626890.49261620.2796596 0.1543862

?

Rotation:

?

??????????????????????? PC1????????? PC2?????????? PC3??????? PC4

?

Sepal.Length? 0.36138659-0.65658877? 0.58202985?0.3154872

?

Sepal.Width? -0.08452251-0.73016143 -0.59791083 -0.3197231

?

Petal.Length0.85667061? 0.17337266 -0.07623608-0.4798390

?

Petal.Width? 0.35828920?0.07548102 -0.54583143? 0.7536574

?

#显示不同PCA方法产生的参数

?

> names (pca1)

?

[1]"sdev"????"loadings""center"??"scale"??"n.obs"??? "scores"? "call"?

?

> names (pca2)

?

[1]"sdev"????"rotation""center"??"scale"??"x"?????

?

#显示不同PCA方法产生的成分

?

> loadings(pca1)

?

Loadings:

?

??????????? Comp.1????????? Comp.2??????? Comp.3??????? Comp.4

?

Sepal.Length???? 0.361????????? -0.657??????????? -0.582??????? 0.315

?

Sepal.Width??????????????????? -0.730????????? 0.598????????? -0.320

?

Petal.Length??? 0.857???????? 0.173????? -0.480?????????????

?

Petal.Width???? 0.358?????????????????????????????? 0.546?????? ??0.754

?

????????????? Comp.1?? Comp.2??Comp.3?? Comp.4

?

SS loadings????? 1.00????1.00????? 1.00????? 1.00

?

Proportion Var??? 0.25?????0.25????? 0.25????? 0.25

?

Cumulative Var?? 0.25????0.50????? 0.75????? 1.00

?

> pca2$rotation

?

??????????????????????? PC1????????? PC2?????????? PC3????????? PC4

?

Sepal.Length? 0.36138659-0.65658877? 0.58202985?0.3154872

?

Sepal.Width? -0.08452251-0.73016143 -0.59791083 -0.3197231

?

Petal.Length0.85667061? 0.17337266 -0.07623608-0.4798390

?

Petal.Width? 0.35828920?0.07548102 -0.54583143? 0.7536574

?

#利用PC1, PC2, PC3绘图

?

> library(plot3D)

?

>scatter3D(pca1loadings[1:4,1],pca1loadings[1:4,1],pca1loadings[1:4,2],pca1$loadings[1:4, 3], colvar=NULL,col=c("red", "black","green", "blue"),pch=20, bty="g", cex=4, phi=6,xlab="PC1",ylab="PC2", zlab="PC3",ticktype="detailed",xlim=c(-0.5,1), zlim=c(-1, 1))

?

?

>scatter3D(pca2rotation[1:4,1],pca2rotation[1:4,1],pca2rotation[1:4,2],pca2$rotation[1:4, 3], colvar=NULL,col=c("red", "black","green", "blue"),pch=20, bty="g", cex=4, phi=6,xlab="PC1",ylab="PC2", zlab="PC3",ticktype="detailed",xlim=c(-0.5,1), zlim=c(-1, 1))

?

----------