In this lab, we will explore principal component analysis (PCA), a technique for identifying patterns among quantitative variables and summarizing data using fewer dimensions (variables).
Note: Some of the mathematical ideas below come from linear algebra. You do not need to have taken linear algebra to complete this lab. The goal is to understand what the mathematics is describing and see one reason why studying linear algebra can be useful.
# load the following packages
# install.packages("factoextra")
# install.packages("psych")
# install.packages("corrplot")
library(psych)
library(factoextra)
library(ggplot2)
library(dplyr)
library(corrplot)
Previously we’ve relied on data visualization to identify trends, but this becomes difficult when the number of variables is large.
Consider data consisting of \(n\) observations of \(p\) variables, represented by the matrix \(\mathbf{X}\):
\[ \mathbf{X} = \begin{pmatrix} x_{1,1} & x_{1,2} & \cdots & x_{1,p} \\ x_{2,1} & x_{2,2} & \cdots & x_{2,p} \\ \vdots & \vdots & \ddots & \vdots \\ x_{n,1} & x_{n,2} & \cdots & x_{n,p} \end{pmatrix} \]
Our goal is to identify patterns across the variables (columns) of \(\mathbf{X}\) using principal component analysis (PCA), producing interpretable, lower-dimensional representations of the main trends in our data.
\(~\)
The main idea behind PCA for dimension reduction is as follows:
Consider the following example:
In Scenario A, the variables X and Y are redundant:
In Scenario B, there is little redundancy between X and Y:
At first, this might seem counterintuitive! In much of statistics, we are interested in relationships between variables. For example, if we wanted to use linear regression to predict Y from X, Scenario A would be more promising because the variables have a strong relationship. Scenario B, where the variables are uncorrelated, would be less useful for this purpose.
PCA has a different goal. Rather than predicting one variable from another, we want to describe our data using fewer dimensions. In Scenario A, the strong relationship between X and Y suggests overlapping information, allowing us to summarize much of their variation using just one dimension. In Scenario B, reducing to one dimension would lose considerably more information.
The next figure shows the first principal component (red) and second principal component (blue) for each scenario:
The first (red) component captures the maximum possible variation in the data, while the second (blue) component is orthogonal (perpendicular) to the first. Because these directions are perpendicular, the component scores are uncorrelated.
We can now describe each observation using these new axes, \(\{PC_1, PC_2\}\), rather than \(\{X,Y\}\). In Scenario A, the \(PC_2\) coordinates have so little variation that we lose little information by ignoring them and using only \(PC_1\), reducing two dimensions to one.
\(~\)
The pictures above illustrate a change of coordinates. Imagine describing a location on a map using east-west and north-south distances. Rotating the map’s axes changes the coordinates without moving the location itself. Similarly, PCA constructs new axes from the original variables, choosing the first to capture the greatest variation, then a perpendicular second axis to capture as much remaining variation as possible.
Each new coordinate is a linear combination (weighted sum) of the original variables. For \(p\) variables, the first two principal components are
\[ PC_1 = \phi_{11}X_1 + \phi_{21}X_2 + \cdots + \phi_{p1}X_p \]
\[ PC_2 = \phi_{12}X_1 + \phi_{22}X_2 + \cdots + \phi_{p2}X_p. \]
The coefficients \(\phi_{11},\phi_{21},\ldots\) are called loadings. They determine how the original variables are combined to construct each new axis. For example, if two standardized variables have loadings of approximately \(0.7\) on the first component, then \(PC_1 \approx 0.7Z_1 + 0.7Z_2\). Observations with high values of both variables would have high scores on that component. Negative loadings mean that larger original values decrease the component score. (The overall sign of a component can be reversed without changing the PCA.)
A score is the value of a principal component for an individual observation, calculated using its original variable values and the loadings. The loadings describe the axes; the scores describe where observations fall on those axes.
A principal component is therefore a new variable constructed to maximize its variance, or the spread of observations along that dimension. Greater variation captures more of the differences between observations. The first component captures the greatest possible variation, while subsequent components capture as much remaining variation as possible without being correlated with previous components.
Before applying PCA, we usually center each variable by subtracting its mean. In this lab, we will also standardize by dividing by the standard deviation. This puts variables on comparable scales, preventing those measured in larger numerical units from dominating the analysis. Standardization is often useful, but not always necessary.
Where does linear algebra enter? A matrix is a rectangular arrangement of numbers. Our data matrix \(\mathbf X\) has one row per observation and one column per variable. After centering the columns, the covariance matrix summarizes how the variables vary together:
\[ \mathbf C = \frac{1}{n-1}\mathbf X^T\mathbf X. \]
Here, \(\mathbf X^T\) is the transpose of \(\mathbf X\) (its rows and columns are exchanged). Linear algebra provides a technique called eigendecomposition that identifies special directions of this covariance matrix:
\[ \mathbf C = \mathbf V\mathbf L\mathbf V^T. \]
The columns of \(\mathbf V\) are called eigenvectors, which give the directions (loadings) of the principal components. The diagonal entries of \(\mathbf L\) are called eigenvalues, which give the variance of each corresponding component. The first component has the largest eigenvalue, the second has the next largest, and so on. You do not need to calculate an eigendecomposition for this lab, but it explains mathematically how PCA identifies these directions. A linear algebra course develops the tools to understand why this works.
\(~\)
\(~\)
The following example uses the USArrests dataset, which
contains state-level statistics on violent crime, including murder,
assault, and rape. Each crime variable is a rate reported in incidents
per 100,000 people.
data("USArrests")
head(USArrests)
If we create a scatterplot matrix (using
pairs()), we see signs of redundancy, particularly between
“Assault” and “Murder”:
## Step 1 - check for signs of redundancy
pairs(USArrests, lower.panel = NULL)
Question 1: Explain what I mean by redundancy in terms of two quantitative variables.
For this analysis, we will standardize the data using
scale():
## Step 2 - standardize the numeric variables
USArrests_std = scale(USArrests)
Question 2: What are some benefits of standardizing quantitative variables when performing statistical analyses? Explain briefly.
We then use the prcomp() function to find the principal
components:
## Step 3 - perform PCA on the standardized data
P = prcomp(USArrests_std)
P$rotation
## PC1 PC2 PC3 PC4
## Murder -0.5358995 -0.4181809 0.3412327 0.64922780
## Assault -0.5831836 -0.1879856 0.2681484 -0.74340748
## UrbanPop -0.2781909 0.8728062 0.3780158 0.13387773
## Rape -0.5434321 0.1673186 -0.8177779 0.08902432
The following optional demonstration uses singular value decomposition (SVD) on the covariance matrix. For a symmetric covariance matrix, SVD recovers the same principal directions as eigendecomposition (up to possible sign changes). You do not need to understand or reproduce this code:
n = nrow(USArrests) ## find n obs
C = 1/(n-1) * t(USArrests_std) %*% USArrests_std ## find Cov matrix
P2 = svd(C) ## singular value decomposition (C = UDV^T)
P2$u ## principal directions (signs may differ from P$rotation)
## [,1] [,2] [,3] [,4]
## [1,] -0.5358995 0.4181809 -0.3412327 0.64922780
## [2,] -0.5831836 0.1879856 -0.2681484 -0.74340748
## [3,] -0.2781909 -0.8728062 -0.3780158 0.13387773
## [4,] -0.5434321 -0.1673186 0.8177779 0.08902432
Finally, let’s find the scores of each state in \(PC_1\) and \(PC_2\) and graph the states in these new dimensions:
scores = as.data.frame(P$x)
scores$State = rownames(P$x) ### row names were used to store states
ggplot(data = scores, aes(x = PC1, y = PC2, label = State)) + geom_text()
We can look at a few states to help us further understand the usefulness of PCA:
Question 3: Perform PCA on the original
USArrests data without standardizing (use
prcomp(USArrests)). Compare the loadings of the first
component with those from the standardized analysis. Which variable
dominates the first component without standardization? Why might that
happen?
Question 4: Describe the states South Carolina and Wisconsin using the graph displayed above.
The code below creates a subset of the “colleges2019” data set with no missing data in the variables that are selected:
colleges = read.csv("https://NFriedrichsen.github.io/data/Colleges2019.csv")
cd = colleges |>
select(Name, State, Enrollment, Adm_Rate, ACT_median,
Net_Tuition, FourYearComp_Males, FourYearComp_Females,
Debt_median, Salary10yr_median)
cd = cd[complete.cases(cd),] ## Keeps only complete cases (no missing values)
The USArrests data already used row
names to identify each state. Notice how we recovered those
names from the PCA scores using rownames(P$x) when making
the plot. Our college data instead have college names in a column called
Name. Since PCA uses numeric variables, we need to leave
Name (and State) out of the analysis, but we
still want to know which college each score belongs to.
We can assign the college names to the row names of
cd before removing the nonnumeric columns:
rownames(cd) = make.unique(as.character(cd$Name))
The rownames() function stores labels for the
observations without treating them as an additional variable.
make.unique() ensures that the row names are unique if two
colleges share a name. When we select and standardize the numeric
columns, these row labels are carried along into the PCA scores. We can
retrieve them later with rownames(PC$x), just as we did
with USArrests. In most data manipulation tasks, it is
preferable to keep identifiers in ordinary columns, but row names are
convenient for this particular PCA workflow.
In the questions that follow you will progress through the basic steps of PCA:
Question 5 (Part A): Create a new data frame where all the numeric variables are standardized. To do this you must remove the “Name” and “State” columns, while keeping the college names as row labels. Why might these row labels be useful when interpreting PCA results?
Question 5 (Part B): Perform PCA using the
prcomp() function. Then, considering only loadings above
0.4 in absolute value (a commonly used threshold), come up with a label
for the first principal component.
Question 5 (Part C): Considering only loadings above 0.4 in absolute value (a commonly used threshold), come up with a label for the second principal component.
Question 5 (Part D): Suppose a college has a large positive score on the first principal component. Based on the loadings you examined in Part B, what characteristics would you expect this college to have? Explain your reasoning.
Question 5 (Part E): Using geom_text()
create a graphic that displays the \(PC_1\) and \(PC_2\) scores of all colleges in
Iowa. Briefly comment on the position of Grinnell College in this
graph, mentioning why you think its location is so far from the other
Iowa colleges.
\(~\)
Principal component analysis is useful when your data contain several numeric variables that are related with each other such that they might be measuring variation in the same underlying factor.
One useful first step in deciding whether PCA may be informative is
to look at the pairwise relationships between variables. The
corrplot package provides several useful functions for
this. Demonstrated below are a few of the package’s functions:
## change R code chunk to {r, fig.width=9, fig.height=7}
## Create the correlation matrix (dropping identifiers)
cormat = cor(select(cd, -Name,-State))
## Default Corrplot
corrplot(cormat)
## Mixed corrplot
corrplot.mixed(cormat, tl.pos = 'lt', tl.cex = 0.5, number.cex = 0.55)
In the second example, the argument tl.pos moves the
text labels to the left and top, “tl”. You could also place them on the
diagonal using “d”. The arguments tl.cex and
number.cex change the size of the text labels and
correlation coefficients (respectively).
## alternative version
corrplot(cormat,
method = "color", type = "lower", tl.col = "black", tl.srt = 45, tl.cex = 0.8)
Question 6: Notice the grouping of variables with dark blue circles in the center of the corrplot. How does this grouping relate to the first principal component you described in Question 5? How would you explain this relationship?
\(~\)
Principal components are linear combinations of the original variables. For standardized data, larger absolute loadings generally indicate a stronger role in defining a component. Because loadings can be negative, it is useful to examine squared loadings when comparing contributions.
The fviz_contrib() function provides a convenient way to
visualize variable contributions:
P = prcomp(USArrests_std)
fviz_contrib(P, choice = "var", axes = 1, top = 4) ## PC1
fviz_contrib(P, choice = "var", axes = 2, top = 3) ## PC2
The bars show each variable’s percentage contribution to the selected component, based on its squared loading. The horizontal reference line shows the percentage each variable would contribute if all variables contributed equally to that component (100% divided by the number of variables). Variables above the line contribute more than this equal-share benchmark.
Question 7: Use fviz_contrib() to
display the contributions of variables to the first principal component
in the PCA of the “colleges” data you performed in Question 5. Do the
variables that appear above the reference line correspond with the ones
you mentioned in Part B of Question 5? Briefly explain.
\(~\)
Principal components are constructed so that earlier components explain more variability in the data than the later components. Thus, not all components are equally valuable - but how should we decide which to keep and interpret and which to discard?
Recall that the matrix \(\mathbf{L}\) contains the eigenvalues of the covariance matrix. For centered, standardized data, these values sum to \(p\) (the number of variables), because each standardized variable has variance 1. Dividing an eigenvalue by the sum of all eigenvalues gives the proportion of variation explained by that component.
Note that the prcomp() function will report the square
root of the eigenvalues:
P = prcomp(USArrests_std) ## US Arrests data
sum(P$sdev^2) ## Recall there were 4 variables
## [1] 4
A popular graphic for visualizing explained variation is the scree plot:
fviz_screeplot(P)
The x-axis displays each principal component, while the y-axis displays the corresponding percentage of variance explained by that component. For the “USArrests” data, the first two principal components account for nearly 90% of variation across different states.
We can find the precise y-values of this graph ourselves by dividing the eigenvalues by \(p\) (the number of columns of the original data):
P$sdev^2/ncol(USArrests_std)
## [1] 0.62006039 0.24744129 0.08914080 0.04335752
Question 8: Construct a scree plot for the PCA you performed on the “colleges” data in Question 5. Next, use the PCA results to find the exact proportion of variation explained by the first three components (i.e., calculate and sum the y-values displayed on your scree plot for \(PC_1\), \(PC_2\), and \(PC_3\)).
\(~\)
Depending on the goals of an analysis, you might subjectively choose to retain a certain number of principal components by inspecting the scree plot.
Alternatively, some suggest retaining all components that explain at least as much variation as a variable in the original data. This corresponds to an eigenvalue \(\geq 1\) or explained variation \(\geq 1/p\).
While popular, neither these methods are particularly rigorous. A more reliable way to determine the number of components to retain is parallel analysis.
Parallel analysis is a statistical approach that compares the
eigenvalues of the real data to a distribution of those found in
randomly generated data of the same size (think of a
randomization test from Sta-209). We can perform parallel analysis using
the fa.parallel() function in the psych
library:
fa.parallel(USArrests_std, fa = "pc") ## fa = "pc" indicates PCA
## Parallel analysis suggests that the number of factors = NA and the number of components = 1
For the “USArrests” data, this parallel analysis suggests retaining only the first principal component (which we previously labeled “overall violent crime”).
Question 9 (Part A): Perform parallel analysis on the “colleges” data that you have used in the previous several questions. Report the number of components that the method suggests should be retained.
Question 9 (Part B): Compare the number of components recommended by parallel analysis with what you might choose from the scree plot in Question 8. Do the two approaches suggest a similar number of components? Briefly explain.
\(~\)
A biplot is a commonly used graph that combines the scores of individual observations and the loadings of the original variables on two principal component axes. The arrows show directions in which the original variable values increase. Arrows pointing in similar directions suggest a positive association between variables; arrows pointing in opposite directions suggest a negative association. These are approximate visual interpretations, and arrow lengths and angles depend on the biplot scaling.
fviz_pca_biplot(P, axes = c(1,2), repel = TRUE) ## PC1 and PC2 for USArrests
Notice how the argument repel = TRUE can be used to
prevent text labels from overlapping.
Question 10: Explain what we can learn from this graph. What extra information is provided compared to what we’ve seen before?