diff --git a/ch10/8.Rmd b/ch10/8.Rmd index c7a858a..fb1d63a 100644 --- a/ch10/8.Rmd +++ b/ch10/8.Rmd @@ -18,17 +18,8 @@ pve ### b ```{r} -loadings = pr.out$rotation -pve2 = rep(NA, 4) -dmean = apply(USArrests, 2, mean) -dsdev = sqrt(apply(USArrests, 2, var)) -dsc = sweep(USArrests, MARGIN=2, dmean, "-") -dsc = sweep(dsc, MARGIN=2, dsdev, "/") -for (i in 1:4) { - proto_x = sweep(dsc, MARGIN=2, loadings[,i], "*") - pc_x = apply(proto_x, 1, sum) - pve2[i] = sum(pc_x^2) -} -pve2 = pve2/sum(dsc^2) -pve2 +x = scale(as.matrix(USArrests)) +phi = as.matrix(pr.out$rotation) +PVE = colSums((x %*% phi)^2) / sum(x^2) +PVE ``` diff --git a/ch10/8.html b/ch10/8.html index f1f49c7..ecbcbf9 100644 --- a/ch10/8.html +++ b/ch10/8.html @@ -13,10 +13,11 @@
## [1] 0.62006 0.24744 0.08914 0.04336
+## [1] 0.62006039 0.24744129 0.08914080 0.04335752
loadings = pr.out$rotation
-pve2 = rep(NA, 4)
-dmean = apply(USArrests, 2, mean)
-dsdev = sqrt(apply(USArrests, 2, var))
-dsc = sweep(USArrests, MARGIN=2, dmean, "-")
-dsc = sweep(dsc, MARGIN=2, dsdev, "/")
-for (i in 1:4) {
- proto_x = sweep(dsc, MARGIN=2, loadings[,i], "*")
- pc_x = apply(proto_x, 1, sum)
- pve2[i] = sum(pc_x^2)
-}
-pve2 = pve2/sum(dsc^2)
-pve2
-## [1] 0.62006 0.24744 0.08914 0.04336
+x = scale(as.matrix(USArrests))
+phi = as.matrix(pr.out$rotation)
+PVE = colSums((x %*% phi)^2) / sum(x^2)
+PVE
+## PC1 PC2 PC3 PC4
+## 0.62006039 0.24744129 0.08914080 0.04335752