Exercise: eigenvalues in R with eigen()
Goal
By the end of this exercise you should be able to:
- call
eigenand read its$valuesand$vectors, - pull out the \(k\)-th eigenvector (a column) and pair it with its eigenvalue,
- verify \(A\mathbf{v} = \lambda\mathbf{v}\) in R, using
all.equalfor floating-point safety, - reconstruct a matrix with a full set of independent eigenvectors as \(A = V\Lambda V^{-1}\), and as \(A = V\Lambda V^\top\) when it is real symmetric,
- compute a covariance matrix with
covand eigen-decompose it, and show the leading eigenvector points along the main axis of variation.
This is an R-heavy walkthrough day. Run every block, change numbers, and look at the plots. The by-hand intuition from Eigenvalues & eigenvectors is what makes the output meaningful.
Background
For a square matrix \(A\), eigen(A) returns a list:
$values— the eigenvalues. For a symmetric matrix they come largest-first.$vectors— a matrix whose columns are the (unit-length) eigenvectors; column \(k\) pairs with$values[k].
Eigenvectors are unique only up to scale and sign, so R’s unit-length vector may be the negative of your hand answer — same direction, still correct.
Reconstruction. When \(A\) has a full set of independent eigenvectors (it is diagonalizable), form \(V\) from those eigenvectors as columns and \(\Lambda = \text{diag}(\text{eigenvalues})\): \[A = V\,\Lambda\,V^{-1}, \qquad\text{and for symmetric } A:\quad A = V\,\Lambda\,V^\top .\] A real symmetric matrix always has an orthonormal eigenvector basis. A general square matrix need not have enough independent eigenvectors; then \(V\) is singular and the inverse formula does not apply.
Biology. The covariance matrix cov(X) (with samples in rows, features in columns) is symmetric. Its leading eigenvector is the direction of greatest variation — the engine of PCA.
By hand
Just a couple, to keep your Eigenvalues & eigenvectors fluency warm and to predict what R will print.
B1. For \(A = \begin{pmatrix} 2 & 1 \\ 1 & 2 \end{pmatrix}\) you found \(\lambda = 3, 1\) with eigenvectors \((1,1)\) and \((1,-1)\). R returns unit-length vectors — what numbers should appear in eigen(A)$vectors? (Divide each by its length.)
B2. A covariance matrix \(C = \begin{pmatrix} 4 & 2 \\ 2 & 4 \end{pmatrix}\). Predict its two eigenvalues by hand, and say which eigenvector is the leading one (the main axis of variation).
In R
Work through every block in order. Re-run with your own numbers to build intuition.
1. Decompose and read the output
A <- matrix(c(2, 1,
1, 2), nrow = 2, byrow = TRUE)
e <- eigen(A)
e$values # 3 1 (largest first)
e$vectors # eigenvectors in COLUMNS, each length 1
e$values[1] # 3
e$vectors[, 1] # eigenvector paired with lambda = 3
e$vectors[, 2] # eigenvector paired with lambda = 12. Verify the eigen relation
lambda <- e$values[1]
v <- e$vectors[, 1]
A %*% v # should equal lambda * v
lambda * v
# == is unsafe for floats; use all.equal
all.equal(as.vector(A %*% v), lambda * v) # TRUE3. Reconstruct the matrix
V <- e$vectors
Lambda <- diag(e$values)
# formula for a diagonalizable matrix (V must be invertible)
V %*% Lambda %*% solve(V) # rebuilds A
# symmetric shortcut (A is symmetric here)
isSymmetric(A) # TRUE
V %*% Lambda %*% t(V) # also rebuilds A, no inverse needed
crossprod(V) # V^T V = identity -> columns orthonormal4. Biology: covariance and the main axis of variation
set.seed(1)
n <- 200
g1 <- rnorm(n)
g2 <- 0.8 * g1 + rnorm(n, sd = 0.4) # gene 2 tracks gene 1 + noise
X <- cbind(g1, g2) # rows = cells, cols = genes
C <- cov(X) # symmetric 2x2 covariance
ec <- eigen(C)
ec$values # variance along each eigen-axis
pc1 <- ec$vectors[, 1] # leading eigenvector
plot(X, asp = 1, pch = 19, col = "grey40",
xlab = "gene 1", ylab = "gene 2")
m <- colMeans(X)
arrows(m[1], m[2], m[1] + 2*pc1[1], m[2] + 2*pc1[2],
col = "red", lwd = 3)
# red arrow lies along the long axis of the cloudTasks
R1. Run block 1 and confirm eigen(A)$vectors[, 1] matches your B1 prediction (up to sign).
R2. In block 2, replace e$vectors[, 1] with e$vectors[, 2] and e$values[1] with e$values[2], and re-verify \(A\mathbf{v}=\lambda\mathbf{v}\) for the second eigenpair.
R3. Make A non-symmetric, e.g. A <- matrix(c(2, 1, 0, 3), 2, byrow = TRUE). Run eigen(A). Do the eigenvectors come out orthogonal? Check with crossprod(eigen(A)$vectors) — is it the identity? Why or why not?
R4. For block 4, compute the fraction of total variance captured by the leading axis: ec$values[1] / sum(ec$values). (This number is what PCA calls “proportion of variance explained by PC1”.)
R5. Increase the noise: set sd = 1.5 when making g2, rebuild X, C, and ec. How does the leading eigenvalue’s share of the variance change, and what does the cloud look like? Explain in one sentence.
R6. Confirm the symmetric reconstruction numerically: with C and its ec from block 4, check all.equal(unname(C), unname(ec$vectors %*% diag(ec$values) %*% t(ec$vectors))) returns TRUE. unname() ignores the feature labels, which eigen() does not retain on the reconstructed matrix.
R7. (complex eigenvalues) Run eigen(matrix(c(0, -1, 1, 0), 2, byrow = TRUE)). What kind of numbers are the eigenvalues, and how does that match the fact that a \(90^\circ\) rotation has no real eigen-direction (Eigenvalues & eigenvectors)?
Hints
eigen(A)$vectors[, k] is the \(k\)-th eigenvector and pairs with eigen(A)$values[k]. Grabbing a row by mistake gives the wrong vector. See eigen.
A %*% v and lambda * v agree only to ~15 digits because of floating point. Use all.equal(as.vector(A %*% v), lambda * v), which returns TRUE when they match within tolerance. (A %*% v is a column matrix, hence as.vector.)
V <- e$vectors already has eigenvectors in columns. diag(e$values) turns the eigenvalue vector into the diagonal matrix \(\Lambda\). If those columns are independent, the inverse is solve(V); the transpose is t(V). Independence is guaranteed for the real symmetric examples here, but not for every square matrix. For example, the shear \(\begin{pmatrix}1&2\\0&1\end{pmatrix}\) has only one independent eigenvector, so it cannot be reconstructed with \(V\Lambda V^{-1}\).
For symmetric \(A\), eigenvectors are orthonormal, so \(V^{-1} = V^\top\) and crossprod(V) (which is \(V^\top V\), see crossprod) is the identity. For a non-symmetric \(A\) this fails — the eigenvectors are generally not orthogonal.
cov(X) expects samples in rows and features in columns. Build X <- cbind(g1, g2). The result is symmetric: variances on the diagonal, covariance off-diagonal.
Total variance = sum(ec$values). The share along the leading axis is ec$values[1] / sum(ec$values). Increasing gene 2’s noise from sd = 0.4 to 1.5 makes this example’s cloud rounder and lowers the share. Because noise is added only to gene 2, increasing it much further makes that gene’s variance dominate: the leading share eventually rises toward 1, not 0.5.
Solutions
B1. R returns unit-length eigenvectors, so divide each hand vector by its length. Each has length \(\lVert(1,\pm1)\rVert = \sqrt{1^2+1^2} = \sqrt2\). For \(\lambda=3\): \((1,1)/\sqrt2 = (1/\sqrt2,\ 1/\sqrt2) \approx (0.707,\ 0.707)\). For \(\lambda=1\): \((1,-1)/\sqrt2 = (1/\sqrt2,\ -1/\sqrt2) \approx (0.707,\ -0.707)\). So eigen(A)$vectors should print roughly these columns. R may flip the sign of either whole column (an eigenvector is only defined up to sign and scale) — same direction, still correct.
B2. \(C\) has the symmetric pattern \(\begin{pmatrix} a & b \\ b & a \end{pmatrix}\) with \(a = 4\), \(b = 2\), so the eigenvectors are \((1,1)\) and \((1,-1)\): \(C\begin{pmatrix}1\\1\end{pmatrix} = \begin{pmatrix}4+2\\2+4\end{pmatrix} = \begin{pmatrix}6\\6\end{pmatrix} = 6\begin{pmatrix}1\\1\end{pmatrix}\), so \(\lambda = 6\); and \(C\begin{pmatrix}1\\-1\end{pmatrix} = \begin{pmatrix}4-2\\2-4\end{pmatrix} = \begin{pmatrix}2\\-2\end{pmatrix} = 2\begin{pmatrix}1\\-1\end{pmatrix}\), so \(\lambda = 2\). The leading eigenvector (largest eigenvalue, \(\lambda=6\)) is \(\mathbf v=(1,1)\) — the main axis of variation. Check: trace \(4+4 = 8 = 6+2\) ✓. The characteristic equation \((4-\lambda)^2 - 4 = 0\) gives the same \(\lambda = 6, 2\).
R1. Run block 1 and read off the first eigenvector column.
A <- matrix(c(2, 1, 1, 2), nrow = 2, byrow = TRUE)
eigen(A)$vectors[, 1] # 0.7071068 0.7071068 (or its negative)This matches the B1 prediction \((1,1)/\sqrt2 \approx (0.707, 0.707)\), up to an overall sign.
R2. Repeat the verification for the second eigenpair (index 2).
e <- eigen(A)
lambda <- e$values[2] # 1
v <- e$vectors[, 2] # eigenvector for lambda = 1, e.g. (0.707, -0.707)
A %*% v # equals lambda * v
lambda * v # same numbers
all.equal(as.vector(A %*% v), lambda * v) # TRUEBoth A %*% v and lambda * v give the same vector (\(1\cdot v = v\) here), and all.equal returns TRUE, confirming \(A\mathbf v = \lambda\mathbf v\) for the second pair too.
R3. Build the non-symmetric matrix and test orthogonality with crossprod (\(V^\top V\)).
A <- matrix(c(2, 1, 0, 3), nrow = 2, byrow = TRUE) # not symmetric
crossprod(eigen(A)$vectors)
# [,1] [,2]
# [1,] 1.000 0.707
# [2,] 0.707 1.000The off-diagonal entries are not 0, so the result is not the identity — the eigenvectors are not orthogonal. The orthogonality guarantee comes from the spectral theorem, which applies only to symmetric matrices; this \(A\) is not symmetric, so it does not hold.
R4. Compute the share of total variance carried by the leading axis.
ec$values[1] / sum(ec$values) # ~ 0.939About 94% of the variance lies along the leading axis, because the two genes are strongly correlated, producing a thin, elongated cloud. This is exactly what PCA reports as “proportion of variance explained by PC1”.
R5. Rebuild the cloud with more noise on gene 2 and recompute the share.
set.seed(1)
n <- 200
g1 <- rnorm(n)
g2 <- 0.8 * g1 + rnorm(n, sd = 1.5) # noisier than before
X <- cbind(g1, g2)
C <- cov(X)
ec <- eigen(C)
ec$values[1] / sum(ec$values) # ~ 0.82 (was ~0.94)With sd = 1.5, gene 2 is noisier and less tied to gene 1, so the cloud becomes rounder and the leading eigenvalue’s share of total variance drops from about 0.94 to about 0.82 — the two genes share less common variation, so the single leading axis no longer dominates as strongly. (Push the noise much higher and the noisy gene’s own variance eventually dominates instead — try sd = 4 and watch the leading axis swing toward the gene-2 direction.)
R6. Reconstruct the symmetric covariance matrix from its eigen-decomposition and compare.
all.equal(unname(C), unname(ec$vectors %*% diag(ec$values) %*% t(ec$vectors))) # TRUEIt returns TRUE: the symmetric reconstruction \(V\Lambda V^\top\) rebuilds the covariance matrix exactly (within floating-point tolerance). Because \(C\) is symmetric its eigenvectors are orthonormal, so \(V^{-1}=V^\top\) and the transpose form works — no solve() needed.
R7. Decompose the \(90^\circ\) rotation and inspect the eigenvalues.
eigen(matrix(c(0, -1, 1, 0), nrow = 2, byrow = TRUE))$values
# [1] 0+1i 0-1iThe eigenvalues are complex (\(0+1i\) and \(0-1i\)), not real. A \(90^\circ\) rotation moves every real direction, so it has no real eigenvector — the same conclusion as B6 in Eigenvalues & eigenvectors. The characteristic equation \(\lambda^2 + 1 = 0\), i.e. \(\lambda = \pm i\), predicts exactly these imaginary values (B9 in Eigenvalues & eigenvectors).
Where this leads
- PCA (Week 2): today’s
eigen(cov(X))is the heart of PCA. PCA adds mean-centring, projecting samples onto the eigenvectors to get scores, and ordering components by variance explained (your R4 number). It scales to thousands of genes at once. - Markov chains: you will apply a transition matrix repeatedly; the stationary distribution is the eigenvector with eigenvalue \(\lambda = 1\), found with the same
eigen()you used today. - Numerical habit: comparing floats with
all.equaland remembering eigenvectors are sign/scale-free will save you throughout the course.