Skip to main content

Principal Component Analysis

PCA

Standardizing, running PCA with prcomp(), choosing how many components to keep, and reading loadings, scores, and biplots, using the iris data from lecture.
Author

Bill Perry

📥 Download the R script

The data are R’s built-in iris, so there is no file to download.

What PCA does

PCA takes many correlated variables and rotates them into new, uncorrelated axes called principal components (PCs). PC1 points along the direction of greatest variation, PC2 the next greatest at right angles to PC1, and so on. If the first two or three PCs capture most of the variation, you can plot and analyze them instead of every variable.

  • Eigenvalue: the variance captured by a PC.
  • Loadings (eigenvectors): how much each original variable contributes to a PC.
  • Scores: where each observation falls on the new axes.

PCA is descriptive: there is no p-value. It assumes roughly linear relationships among the variables.

Data: four flower measurements (cm) on 150 irises of three species. Species is not used to build the PCA; we only use it to color the plot afterwards.

Step 1: Load packages and data

library(tidyverse)
library(janitor)      # clean_names()
library(factoextra)   # fviz_eig(), fviz_pca_var(), fviz_pca_biplot()

iris_df <- iris %>% clean_names()

iris_data <- iris_df %>%
  dplyr::select(sepal_length, sepal_width, petal_length, petal_width)

head(iris_data)
  sepal_length sepal_width petal_length petal_width
1          5.1         3.5          1.4         0.2
2          4.9         3.0          1.4         0.2
3          4.7         3.2          1.3         0.2
4          4.6         3.1          1.5         0.2
5          5.0         3.6          1.4         0.2
6          5.4         3.9          1.7         0.4

Step 2: Look at the correlations

PCA is only useful if the variables are correlated.

round(cor(iris_data), 2)
             sepal_length sepal_width petal_length petal_width
sepal_length         1.00       -0.12         0.87        0.82
sepal_width         -0.12        1.00        -0.43       -0.37
petal_length         0.87       -0.43         1.00        0.96
petal_width          0.82       -0.37         0.96        1.00

The petal measurements and sepal length are strongly correlated, so a few PCs should summarize them well.

Step 3: Standardize

Variables on different scales must be standardized (mean 0, SD 1), or the variable with the largest variance dominates.

iris_scaled <- scale(iris_data)

round(colMeans(iris_scaled), 3)        # all 0
sepal_length  sepal_width petal_length  petal_width 
           0            0            0            0 
round(apply(iris_scaled, 2, sd), 3)    # all 1
sepal_length  sepal_width petal_length  petal_width 
           1            1            1            1 

Step 4: Run the PCA

iris_pca <- prcomp(iris_scaled, center = FALSE, scale. = FALSE)

summary(iris_pca)
Importance of components:
                          PC1    PC2     PC3     PC4
Standard deviation     1.7084 0.9560 0.38309 0.14393
Proportion of Variance 0.7296 0.2285 0.03669 0.00518
Cumulative Proportion  0.7296 0.9581 0.99482 1.00000

center and scale. are FALSE because scale() already did both. (Giving raw data to prcomp(..., scale. = TRUE) is identical.)

Reading the output: Proportion of Variance is each PC’s share; Cumulative Proportion adds them up.

Step 5: How many PCs to keep?

eigenvalues <- iris_pca$sdev^2
eigenvalues
[1] 2.91849782 0.91403047 0.14675688 0.02071484
fviz_eig(iris_pca, addlabels = TRUE)

Common rules: keep PCs with eigenvalue > 1 (Kaiser), or keep PCs before the “elbow” in the scree plot, or keep enough to explain ~80–90%. Here PC1 and PC2 explain about 96%.

Step 6: Loadings — what do the PCs mean?

round(iris_pca$rotation, 2)
               PC1   PC2   PC3   PC4
sepal_length  0.52 -0.38  0.72  0.26
sepal_width  -0.27 -0.92 -0.24 -0.12
petal_length  0.58 -0.02 -0.14 -0.80
petal_width   0.56 -0.07 -0.63  0.52
  • PC1: sepal length and both petal measurements load strongly with the same sign. PC1 is overall flower size.
  • PC2: dominated by sepal width.

The sign of a PC is arbitrary; only the relative signs within a PC matter.

fviz_pca_var(iris_pca, col.var = "contrib", repel = TRUE)

Arrows pointing the same way are positively correlated; longer arrows are better represented by these two PCs.

Step 7: Scores and the biplot

fviz_pca_biplot(iris_pca,
                geom.ind = "point",
                col.ind = iris_df$species,
                addEllipses = TRUE,
                repel = TRUE,
                legend.title = "Species")

The species separate along PC1: setosa has small petals, virginica large. The scores can be saved for later analysis:

scores_df <- as_tibble(iris_pca$x) %>%
  mutate(species = iris_df$species)

head(scores_df)
# A tibble: 6 × 5
    PC1    PC2     PC3      PC4 species
  <dbl>  <dbl>   <dbl>    <dbl> <fct>  
1 -2.26 -0.478  0.127   0.0241  setosa 
2 -2.07  0.672  0.234   0.103   setosa 
3 -2.36  0.341 -0.0441  0.0283  setosa 
4 -2.29  0.595 -0.0910 -0.0657  setosa 
5 -2.38 -0.645 -0.0157 -0.0358  setosa 
6 -2.07 -1.48  -0.0269  0.00659 setosa 

Step 8: Write it up

A PCA on the correlation matrix of four standardized flower measurements produced two components that together explained 96% of the variation (PC1 73%, PC2 23%). PC1 reflected overall flower size (high loadings for petal length, petal width, and sepal length); PC2 reflected sepal width. The three species separated mainly along PC1.

Report whether variables were standardized, the variance explained by each retained PC, how you chose how many to keep, what the loadings mean, and show the biplot.