---
title: "Lab 10 Solutions"
output: pdf_document
---

#### 1)	Calculate the mean and variance of each column, by using apply() function.
```{r}
states <- row.names(USArrests)
states
names(USArrests)

apply(USArrests, 2, mean)
apply(USArrests, 2, var)
```

#### 2)	What conclusions can you draw from 1)? And consequently what transformation would you do to your dataset?

We see that there are on average three times as many
rapes as murders, and more than eight times as many assaults as rapes.

Not surprisingly, the variables also have vastly different variances: the
UrbanPop variable measures the percentage of the population in each state
living in an urban area, which is not a comparable number to the number
of rapes in each state per 100,000 individuals. 

If we failed to scale the
variables before performing PCA, then most of the principal components
that we observed would be driven by the Assault variable, since it has by
far the largest mean and variance. Thus, it is important to standardize the
variables to have mean zero and standard deviation one before performing
PCA.

#### 3)	Perform principal component analysis using the prcomp() function.
```{r}
pr.out <- prcomp (USArrests , scale = TRUE)
```

#### 4)	Check the results, report the number of PCs and their center, scale, and rotation.
```{r}
names(pr.out)

pr.out$center   #Don't write it as "centre"!
pr.out$scale
pr.out$rotation
```

#### 5)	Plot the first two PCs.
```{r}
biplot(pr.out, scale = TRUE)
```

#### 6)	What are the standard deviation of each principal component? Based on this result, calculate the variance explained by each PC and the proportion of variance explained by each PC.
```{r}
pr.out$sdev
pr.var <- pr.out$sdev^2
pr.var

pve <- pr.var/sum(pr.var)
pve
```

#### 7)	Plot the PVE explained by each component as well as the cumulative PVE. 
```{r}
plot(pve, 
     xlab = " Principal Component", ylab = " Proportion of Variance Explained", 
     ylim=c(0,1), type='b')

plot(cumsum(pve), 
     xlab = " Principal Component ", ylab =" Cumulative Proportion of Variance Explained", 
     ylim = c(0,1), type = 'b')
```


