In base R the recommended function is prcomp()
. Read its help file ?prcomp
.
例如:
mod <- prcomp(USArrests, scale = TRUE)
<代码>mod 然后成为prcomp>
的物体,而单向导体矩阵(主要部件、正本/未计)则载于构成部分。
> str(mod)
List of 5
$ sdev : num [1:4] 1.575 0.995 0.597 0.416
$ rotation: num [1:4, 1:4] -0.536 -0.583 -0.278 -0.543 0.418 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:4] "Murder" "Assault" "UrbanPop" "Rape"
.. ..$ : chr [1:4] "PC1" "PC2" "PC3" "PC4"
$ center : Named num [1:4] 7.79 170.76 65.54 21.23
..- attr(*, "names")= chr [1:4] "Murder" "Assault" "UrbanPop" "Rape"
$ scale : Named num [1:4] 4.36 83.34 14.47 9.37
..- attr(*, "names")= chr [1:4] "Murder" "Assault" "UrbanPop" "Rape"
$ x : num [1:50, 1:4] -0.976 -1.931 -1.745 0.14 -2.499 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:50] "Alabama" "Alaska" "Arizona" "Arkansas" ...
.. ..$ : chr [1:4] "PC1" "PC2" "PC3" "PC4"
- attr(*, "class")= chr "prcomp"
查阅<代码>x构成部分:
> head(mod$x)
PC1 PC2 PC3 PC4
Alabama -0.9756604 1.1220012 -0.43980366 0.154696581
Alaska -1.9305379 1.0624269 2.01950027 -0.434175454
Arizona -1.7454429 -0.7384595 0.05423025 -0.826264240
Arkansas 0.1399989 1.1085423 0.11342217 -0.180973554
California -2.4986128 -1.5274267 0.59254100 -0.338559240
Colorado -1.4993407 -0.9776297 1.08400162 0.001450164
Extract components 1 and 2
> scrs <- mod$x[, 1:2]
> head(scrs)
PC1 PC2
Alabama -0.9756604 1.1220012
Alaska -1.9305379 1.0624269
Arizona -1.7454429 -0.7384595
Arkansas 0.1399989 1.1085423
California -2.4986128 -1.5274267
Colorado -1.4993407 -0.9776297
之后,你可以规划他们:
plot(scrs, asp = 1) ## asp = 1 gives equal scaling to x and y axes