From 5f2bbddad60c2aced7a99f371022ffca08398143 Mon Sep 17 00:00:00 2001 From: jabbermonkey Date: Thu, 6 Aug 2015 22:00:57 -0400 Subject: [PATCH 1/2] Update 8.Rmd Simplified code for Chapter 10, Question 8(b) --- ch10/8.Rmd | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) 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 ``` From e0425a00926a199f99edf2e808c50647ba0e63bf Mon Sep 17 00:00:00 2001 From: jabbermonkey Date: Thu, 6 Aug 2015 22:14:19 -0400 Subject: [PATCH 2/2] Update 8.html Generated HTML for Chapter 10, excercise 8. Used matrix math to simplify the code in 8(b). --- ch10/8.html | 39 ++++++++++++++++++++------------------- 1 file changed, 20 insertions(+), 19 deletions(-) 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 @@ Chapter 10: Exercise 8 - - - - + + + + + @@ -46,6 +47,14 @@ margin-left: auto; margin-right: auto; } +code { + color: inherit; + background-color: rgba(0, 0, 0, 0.04); +} +img { + max-width:100%; + height: auto; +}
@@ -63,24 +72,16 @@

a

pr.var = pr.out$sdev^2 pve = pr.var / sum(pr.var) pve -
## [1] 0.62006 0.24744 0.08914 0.04336
+
## [1] 0.62006039 0.24744129 0.08914080 0.04335752

b

-
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