Eigenvalues in R with eigen()

Week 2 — Eigenvalues in R

Quantitative biology and integrative omics

About this lecture

In Eigenvalues & eigenvectors you found eigenvalues by hand in the simple cases: testing a candidate, diagonal and triangular matrices, the symmetric 2\times2 pattern. Those skills are examined — but most real matrices fit no pattern, and anything bigger than 2\times2 is out of reach by hand. Today R does the arithmetic.

  • eigen returns all eigenvalues and eigenvectors at once.
  • Read its output: $values and $vectors, and how eigenvectors sit in the columns.
  • R sorts eigenvalues from largest to smallest — and normalises eigenvectors to length 1.
  • Verify A\mathbf{v}=\lambda\mathbf{v} in R, and reconstruct A = V\Lambda V^{-1} (and V\Lambda V^\top for symmetric A).
  • Biology payoff: eigen-decompose a small covariance matrix and watch the leading eigenvector point along the main axis of variation in a gene-expression scatter (the engine of PCA).

This is a hands-on R walkthrough: keep an R session open and run every block.

The function: eigen()

Give it a square matrix; get back a list with two parts.

A <- matrix(c(2, 1,
              1, 2), nrow = 2, byrow = TRUE)
e <- eigen(A)
e
# eigen() decomposition
# $values
# [1] 3 1
#
# $vectors
#            [,1]       [,2]
# [1,] 0.7071068 -0.7071068
# [2,] 0.7071068  0.7071068
  • e$values — the eigenvalues, largest first: 3, 1.
  • e$vectors — the eigenvectors, one per column, each length 1.

Reading $vectors: columns, not rows

The eigenvectors are the columns of e$vectors. The i-th column matches the i-th eigenvalue.

e$values[1]        # 3
e$vectors[, 1]     # 0.7071068 0.7071068   <- eigenvector for lambda = 3
e$vectors[, 2]     # -0.7071068 0.7071068  <- eigenvector for lambda = 1
  • e$vectors[, 1] is the eigenvector paired with e$values[1].
  • This is (1,1) from Eigenvalues & eigenvectors, scaled to length 1: 1/\sqrt{2} \approx 0.707.

Scale and sign are not unique

R returns unit-length eigenvectors, but the sign is arbitrary — R might give you \mathbf{v} or -\mathbf{v}.

e$vectors[, 2]            # -0.707  0.707
-e$vectors[, 2]           #  0.707 -0.707   <- equally valid eigenvector
  • Both point along the same line (the eigen-direction); both satisfy A\mathbf{v}=\lambda\mathbf{v}.
  • So if your hand answer is (1,-1) and R prints (-0.707, 0.707), you are not wrong — same direction, opposite sign, unit length.

Verify the eigen relation

Never trust output you haven’t checked. Confirm A\mathbf{v} = \lambda\mathbf{v} directly:

lambda <- e$values[1]      # 3
v      <- e$vectors[, 1]   # unit eigenvector

A %*% v                    # 2.121320 2.121320
lambda * v                 # 2.121320 2.121320   <- identical

all.equal(as.vector(A %*% v), lambda * v)   # TRUE
  • Use all.equal, not ==: floating-point arithmetic gives tiny rounding differences.

Eigenvectors and eigenvalues rebuild the matrix

Stack eigenvectors as columns of V and eigenvalues on the diagonal of \Lambda. Then

A = V\,\Lambda\,V^{-1}

V      <- e$vectors
Lambda <- diag(e$values)        # eigenvalues on the diagonal
V %*% Lambda %*% solve(V)       # rebuilds A
#      [,1] [,2]
# [1,]    2    1
# [2,]    1    2
  • diag turns the eigenvalue vector into a diagonal matrix \Lambda.
  • solve(V) is the inverse V^{-1}.
  • This eigendecomposition says: A = (change to eigen-coords) → (scale each axis by its \lambda) → (change back).

Symmetric shortcut: A = V\Lambda V^\top

For a symmetric matrix, the eigenvectors are orthogonal and unit length (R gives them this way), so V^{-1} = V^\top. No matrix inverse needed:

A = V\,\Lambda\,V^\top

isSymmetric(A)                  # TRUE
crossprod(V)                    # V^T V = identity (cols are orthonormal)
V %*% Lambda %*% t(V)           # rebuilds A, using transpose instead of inverse
  • t(V) is the transpose V^\top; crossprod(V) computes V^\top V.
  • eigen() automatically uses a faster, more accurate symmetric algorithm when it detects symmetry.

Biology: covariance of two genes

Simulate expression of two co-regulated genes across cells, then look at the covariance.

set.seed(1)
n  <- 200
g1 <- rnorm(n)                       # gene 1
g2 <- 0.8 * g1 + rnorm(n, sd = 0.4)  # gene 2 tracks gene 1 (+ noise)
X  <- cbind(g1, g2)                  # n x 2: rows = cells, cols = genes

C <- cov(X)                          # 2 x 2 covariance matrix (symmetric)
round(C, 3)
#       g1    g2
# g1 0.863 0.683
# g2 0.683 0.703
  • cov computes the covariance matrix; it is symmetric by construction.
  • Diagonal = variance of each gene; off-diagonal = how they co-vary (positive → rise together).

The leading eigenvector = main axis of variation

ec <- eigen(C)
ec$values            # 1.470  0.096   (variance along each axis)
pc1 <- ec$vectors[, 1]   # leading eigenvector

plot(X, asp = 1, pch = 19, col = "grey40",
     xlab = "gene 1", ylab = "gene 2")
# draw the leading eigen-direction through the cloud's centre
m <- colMeans(X)
arrows(m[1], m[2], m[1] + 2*pc1[1], m[2] + 2*pc1[2], col = "red", lwd = 3)
  • The largest eigenvalue’s eigenvector (ec$vectors[, 1]) points along the long axis of the cloud.
  • Its eigenvalue is the variance captured along that direction.

Foreshadowing PCA (not today)

What you just did is the core computation of Principal Component Analysis:

Eigen concept (today) PCA name (later this week)
covariance matrix C the thing PCA decomposes
leading eigenvector first principal component (PC1)
its eigenvalue variance explained by PC1
orthogonal eigenvectors uncorrelated principal axes

PCA adds centring, projecting samples onto these axes (scores), and handling many genes at once. We are not doing that yet — today’s job was to see that eigenvectors of the covariance matrix are the axes of variation.

Numerical notes & gotchas

  • Use all.equal, not ==, to compare floats — eigen results carry tiny rounding error.
  • Sign is arbitrary: R may return \mathbf{v} or -\mathbf{v}. Compare directions, not raw numbers.
  • Ordering: eigen() sorts eigenvalues largest-first for symmetric matrices; for general matrices the order is by modulus (and values may be complex).
  • Complex output: a rotation gives 0+1i-style complex eigenvalues — expected, no real eigen-direction.
  • Symmetric flag: if you know A is symmetric, eigen(A, symmetric = TRUE) is faster and guarantees real output (avoids tiny imaginary parts from rounding).

Summary

Task R
Decompose e <- eigen(A)
Eigenvalues (largest first) e$values
Eigenvectors (columns, unit length) e$vectors
The k-th eigenvector e$vectors[, k]
Verify all.equal(as.vector(A %*% v), lambda * v)
Reconstruct (general) V %*% diag(vals) %*% solve(V)
Reconstruct (symmetric) V %*% diag(vals) %*% t(V)
Covariance matrix cov(X) (rows = samples)
Main axis of variation eigen(cov(X))$vectors[, 1]

Next (Markov chains): matrices applied repeatedly — where the eigenvalue \lambda = 1 gives the long-run stationary distribution.