Skip to main content

Problem Set 7: Principal Component Analysis

PLS 206 — Applied Multivariate Modeling

Author

Grey Monroe

Published

January 1, 2026

Note

Due: Monday, November 16, 1:10 PM (start of class) — submitted through Canvas.

Everything here uses Monday’s lecture (PCA, and the tour of other ordination methods). The lecture script L12 PCA intro.R has working code for every step.

Stuck? Every question has a hint. Open it: most hints contain a code skeleton where you only fill in the blanks (___), say what your output should look like, and name the slide that explains the idea.


Submission Instructions

Upload two files to Canvas:

  1. Written answers — a .pdf document with your written responses, interpretations, and figures.
  2. R script — a .R file with all the code you used to produce your answers.

List the first and last names of any collaborators in both files.

Naming convention: HW7emailID.R (code) and HW7emailID.pdf (written answers), where emailID is the part of your UC Davis email before the @.

Example: Grey Monroe would submit HW7gmonroe.R and HW7gmonroe.pdf.

Feel free to use Google, StackOverflow, and other resources if you are stuck with code, and post questions on Slack if anything is unclear.


The data

Wine (Parts 1 to 3). The wine data from Week 1: 13 chemical measurements on 178 wines from three cultivars (barbera, barolo, gringnolino).

Cassava (Part 4). The lecture’s case study: 1006 cassava landraces, the 19 bioclimatic variables of each landrace’s home site, and root dry matter (Dry_matter).

library(ggplot2)
wine    <- read.csv("https://greymonroe.github.io/PLS_206/data/winedata.csv")
cassava <- read.csv("https://greymonroe.github.io/PLS_206/data/cassava.csv")
chem <- wine[, -1]   # the 13 chemical columns (drop Cultivar)

A note on signs. The sign of a principal component is arbitrary: flip every loading and every score of PC1 and nothing about the analysis changes. If your PC1 points the opposite way from a classmate’s, you are both right. Describe directions in terms of the variables (“wines high in Flav”), not “positive PC1”.

The three pieces of a PCA in R (you will use them in almost every question):

You want In R One number per
eigenvalues (variance of each PC) pca$sdev^2 PC
loadings (eigenvectors: the recipe for each PC) pca$rotation variable × PC
scores (each sample’s position on each PC) pca$x sample × PC
% of variance per PC summary(pca)$importance PC

Part 1: Setting Up the PCA

Q1. To scale or not? Report the variance of each of the 13 chemicals. Run prcomp(chem) without scaling and report the share of variance PC1 explains and the variable that dominates its loadings. Explain in a sentence why, and why scale. = TRUE is the right choice here.

sapply(chem, var)                      # 13 variances, one per chemical
pca_raw <- prcomp(chem)                # NOT scaled
summary(pca_raw)$importance[2, 1]      # share of variance in PC1 (0 to 1)
round(pca_raw$rotation[, 1], 3)        # PC1 loadings: which one is near 1 or -1?

Compare the biggest variance with the smallest. Unscaled PCA chases variance, so a variable measured in big numbers takes over. Slide Scale first, or units win.

Q2. Run the scaled PCA, pca <- prcomp(chem, scale. = TRUE). Report the share of variance explained by PC1, PC2 and PC3, and the cumulative share of the first six.

pca <- prcomp(chem, scale. = TRUE)
summary(pca)$importance                # row 2: proportion per PC; row 3: cumulative

Read PC1 to PC3 from row 2 and PC6 from row 3. Proportions are between 0 and 1; report them as percentages. Slide Eigenvalue = the spread of the scores.

Q3. How many PCs would you keep? Use three rules: the elbow of a scree plot, the Kaiser criterion (eigenvalue ≥ 1), and the fewest PCs that explain at least 80% of the variance. Report each answer, include the scree plot, and say in a sentence or two why the rules disagree.

ev <- pca$sdev^2                       # the 13 eigenvalues
plot(pca, type = "l")                  # scree plot: look for where the line flattens
sum(ev >= 1)                           # Kaiser: how many eigenvalues are at least 1
cumsum(ev) / sum(ev)                   # cumulative share after 1, 2, 3, ... PCs
which(cumsum(ev) / sum(ev) >= 0.8)[1]  # the first PC that gets you to 80%

Why 1 for Kaiser? With scaled data every chemical has variance 1, so a PC with eigenvalue below 1 carries less than one chemical’s worth of information. The elbow is a judgement call: any defensible answer is fine. Slide How many PCs to keep?


Part 2: What the Axes Mean

Q4. Compute the correlation between each chemical and PC1 and PC2. Which chemicals have |r| ≥ 0.5 with PC1? With PC2? In one sentence each, describe a wine at one end of PC1 and a wine at one end of PC2 in plain chemical terms.

r <- cor(chem, pca$x[, 1:2])           # 13 rows (chemicals) x 2 columns (PC1, PC2)
round(r, 2)
rownames(r)[abs(r[, "PC1"]) >= 0.5]    # chemicals strongly tied to PC1
rownames(r)[abs(r[, "___"]) >= 0.5]    # same for PC2

To describe one end of PC1: the chemicals with large positive r are high there, and the ones with large negative r are low. Slide Loadings as correlations.


Part 3: The Wines in PC Space

Q5. Plot the wines’ scores on PC1 (x) against PC2 (y), coloured by cultivar, with axis labels that give each PC’s percentage of variance and coord_fixed(). Do the three cultivars separate? Which PC separates which cultivars, and which chemicals (from Q4) drive that separation?

scores <- data.frame(pca$x, Cultivar = wine$Cultivar)
pct <- round(100 * pca$sdev^2 / sum(pca$sdev^2))     # % variance of every PC
ggplot(scores, aes(x = PC1, y = ___, colour = ___)) +
  geom_point() +
  coord_fixed() +
  labs(x = paste0("PC1 (", pct[1], "%)"), y = paste0("PC2 (", pct[2], "%)"),
       colour = "Cultivar") +
  theme_classic()
aggregate(cbind(PC1, PC2) ~ Cultivar, data = scores, FUN = mean)   # each cultivar's centre

Read the cultivar centres: two cultivars far apart on PC1 are separated by PC1. Then use Q4 to say which chemicals make PC1. Slide PCA never sees the groups.

Q6. A new, unlabeled wine arrives with these measurements. Place it in the PC space of Q5 with predict(), report its PC1 and PC2 scores, and say which cultivar it most likely belongs to.

new_wine <- data.frame(Alcohol = 13.75, AlcAsh = 16.8, Ash = 2.44, Color = 5.4,
                       Flav = 2.98, Hue = 1.07, MalicAcid = 1.77, Mg = 104,
                       NonFlavPhenols = 0.29, OD = 3.0, Phenols = 2.8,
                       Proa = 1.87, Proline = 1095)
nw <- predict(pca, newdata = new_wine)[, 1:2]   # its PC1 and PC2 scores
nw
# add it to your Q5 plot as a big black point:
#   + annotate("point", x = nw[1], y = nw[2], size = 5)

predict() scales the new wine with the original wines’ means and SDs, then applies the same recipe (loadings). It lands closest to which cultivar’s centre from Q5? Slide Score = one sample’s position on PC1.


Part 4: PCs as Predictors

Q7. Fit lm(Dry_matter ~ ., data = cassava). Why does car::vif() fail on this model? (Look at alias() and at what bio7 is.) Drop bio7, refit, and report the largest VIF.

m_all <- lm(Dry_matter ~ ., data = cassava)
alias(m_all)$Complete                  # shows bio7 as an exact combination of two others
m18 <- lm(Dry_matter ~ . - bio7, data = cassava)
sort(car::vif(m18), decreasing = TRUE)[1:3]

bio7 is the annual temperature range: the warmest month’s maximum (bio5) minus the coldest month’s minimum (bio6). When one column is an exact sum of others, lm() cannot give it its own slope. Slide 19 columns, only a few signals; Week 5’s VIF slides.

Q8. Run a scaled PCA on the 19 climate variables and fit Dry_matter ~ PC1 + PC2 + PC3. Report each coefficient with its p-value, the VIFs, and R². Then use the PC1 loadings to say in words what a landrace with a high PC1 score experiences at home, and what the PC1 coefficient means for dry matter. Plot Dry_matter against PC1 with the fitted line and its 95% confidence band.

pc <- prcomp(cassava[, 1:19], scale. = TRUE)          # columns 1-19 are the climate variables
d <- data.frame(Dry_matter = cassava$Dry_matter, pc$x[, 1:3])
m_pc <- lm(Dry_matter ~ PC1 + PC2 + PC3, data = d)
summary(m_pc)                                          # coefficients, p-values, R-squared
car::vif(m_pc)                                         # what do you expect for uncorrelated PCs?
round(sort(pc$rotation[, 1]), 2)                       # PC1 loadings, smallest to largest
ggplot(d, aes(PC1, Dry_matter)) +
  geom_point(alpha = 0.3) +
  geom_smooth(method = "lm") +                         # line + 95% band
  theme_classic()

To name PC1: which kind of variable (temperature or rainfall) has the biggest loadings, and are they positive or negative? If temperature loads negatively, a high PC1 score means a cooler home site. Then combine that with the sign of the PC1 coefficient. Slides Read the loadings to name each PC and PCs as predictors.

Q9. The 18-variable model from Q7 has a higher R² than the three-PC model. Give one reason to prefer the three-PC model anyway, and one thing you give up by using it.

Compare summary(m18)$r.squared with summary(m_pc)$r.squared. Think about two things. With VIFs in the thousands, can you trust or interpret the 18 separate slopes? And a PC is a blend of 19 variables: can a grower measure or change “PC1”? Also note that PCA picked the PCs to describe the climate, not to predict dry matter (slide PCs as predictors: a PC with little climate variance can still matter).


Part 5: Choosing a Method

Q10. For each study, choose PCA, PCoA, NMDS, or UMAP/t-SNE, and justify it in one sentence (the table on the module page will help):

  1. Ten leaf traits (mm, g, %) measured on 300 oak trees; you want a “leaf economics” axis to use as a predictor in a model of growth.
  2. Counts of 85 insect species in 40 traps, most of them zeros; you want to see whether traps in organic and conventional fields hold different communities.
  3. Expression of 20,000 genes in 15,000 single cells; you want a picture of the cell types for a figure.
  4. A matrix of pairwise genetic distances among 120 accessions, with no raw genotypes.

Ask two questions of each study. What do you start from? Measured variables, or only distances between samples? What do you need? Axes you can interpret and reuse in a model, or only a picture? PCA needs the variables and gives interpretable axes; PCoA and NMDS start from a distance matrix (NMDS keeps only the order of the distances and is the usual choice for species counts with many zeros); UMAP and t-SNE are for pictures of very large data. Slide Which method, when?