-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhw03.Rmd
76 lines (53 loc) · 1.8 KB
/
hw03.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
---
title: "GEOG606 - HW03"
author: "Anika Cartas"
date: "Tuesday, March 24, 2015"
output: word_document
---
### Assignment Description
In 1898, Bumpus did a series study of English sparrows. Attached is his measurement of characteristics of 49 female sparrows:
X1=total length
X2=alar length,
X3=length of beak and head,
X4=length of humerus,
X5=length of keel and sternum.
Please use principle component analysis to find out the linear combination of 5 variables that best discriminates different sparrows. First, use the PCA routine in R to do it.
Second, try to reproduce the result of PCA routine by following the key steps of PCA:
- generate covariance matrix
- solve the eigen value equation to calculate the eigen values
- derive eigen vectors
- calculate loading vectors
###1. Read in the data
```{r}
data <- read.table("hw03.csv",header=TRUE, col.names=c("Total","Alar","Beak.Head","Humerus","Keel.Sternum"))
head(data)
```
###2. Use PCA routine in R
```{r}
prcomp.results <- prcomp(data)
#Rotation Matrix
prcomp.results
#Loading Scores
head(prcomp.results$x)
```
###3. Reproduce results manually
```{r}
#3.1 Zero data by subtracting mean
data.adjusted <- apply(data,2,function(x) { x - mean(x) })
#3.2 Generate covariance matrix
cov.matrix <- cov(data.adjusted)
cov.matrix
#3.3 Solve the eigen value equation to calculate the eigen values
cov.eigen <- eigen(cov.matrix)
cov.eigen$values
#3.4 Derive eigen vectors
cov.eigen$vectors
#3.5 Calculate loading scores
manual.results <- t(cov.eigen$vectors) %*% t(as.matrix(data.adjusted))
manual.results <- t(manual.results)
head(manual.results)
#3.6. Compare Results
head(prcomp.results$x)
#Calculate differences between each value and see if any are not nearly identical.
table(abs(manual.results) - abs(prcomp.results$x) < 0.001)
```