Skip to main content
v2026.11,986 entries · CC-BY 4.0

Principal Component Analysis Steps: Math, Example, and Code

Learn the 5 principal component analysis steps: standardization, covariance, eigendecomposition, component selection, and projection with math and code.

Written and maintained by CASRAI Editorial Board

Published

On this page

Principal component analysis steps comprise five sequential procedures: centering and standardizing the multivariate data matrix, computing the sample covariance or correlation matrix, performing eigendecomposition or singular value decomposition to extract eigenvalues and orthogonal eigenvectors, ranking and selecting leading components based on variance explained, and projecting original observations into the new coordinate space to generate uncorrelated component scores for downstream analysis.

Definition and Purpose of Principal Component Analysis

Principal component analysis (PCA) is an unsupervised multivariate statistical method that reduces dataset dimensionality while preserving maximal variance. Introduced by Karl Pearson in 1901 and extended by Harold Hotelling in 1933, PCA transforms p correlated variables into an equal number of uncorrelated orthogonal linear composites known as principal components.

In quantitative research across bioinformatics, chemometrics, finance, and psychometrics, high-dimensional datasets routinely suffer from multicollinearity and computational overhead. Correlated predictors carry redundant variance that destabilizes regression models and inflates standard errors. PCA addresses these challenges by establishing an ordered orthogonal coordinate system where the first principal component captures maximal sample dispersion, and subsequent components capture remaining orthogonal variance.

PCA operates as an orthogonal rotation that preserves geometric distance structure while aligning coordinates with principal axes of dispersion. Retaining k components where k is substantially smaller than p compresses feature spaces while filtering out random measurement noise.

Mathematical Foundations and Formulas

The mathematical formulation of PCA begins with an n × p observation matrix X containing n observations across p continuous variables. The sample mean vector is x̄ = [x̄₁, …, x̄ₚ]ᵀ. Mean-centered matrix Xc is constructed by subtracting column means: xc,ij = xij − x̄j.

When features differ in measurement units, centered entries are divided by sample standard deviations sj, yielding standardized matrix Z with entries zij = (xij − x̄j) / sj. The sample covariance matrix S of size p × p is computed as:

S = (1 / (n − 1)) Xcᵀ Xc

With standardized variables, this yields correlation matrix R = (1 / (n − 1)) Zᵀ Z. PCA seeks normalized weight vectors v₁ that maximize projected variance Var(Xc v₁) = v₁ᵀ S v₁, subject to v₁ᵀ v₁ = 1. Applying Lagrange multipliers yields the characteristic eigenvalue equation:

(S − λ I) v = 0

where I is the identity matrix, λ is the component eigenvalue, and v is the unit-length eigenvector. Setting characteristic determinant det(S − λ I) = 0 yields p real non-negative eigenvalues ordered λ₁ ≥ λ₂ ≥ … ≥ λₚ ≥ 0. Total sample variance equals the trace of the covariance matrix:

Total Variance = tr(S) = ∑j=1p sjj = ∑i=1p λi

The proportion of variance explained by component i equals λi / ∑ λj. Component scores for observation k on component i are calculated by projection: yki = ∑j=1p xc,kj vji, or in matrix form Y = Xc V. Computational software routinely implements this via Singular Value Decomposition, factoring Xc = U Σ Vᵀ to ensure numerical stability.

The 5 Sequential Principal Component Analysis Steps

Executing principal component analysis requires adhering to five structured procedural steps:

  1. Step 1: Data Preprocessing and Standardization. Inspect raw variables for missingness and outliers. Center each variable by subtracting its sample mean. If variables possess differing measurement units, standardize features to zero mean and unit variance.
  2. Step 2: Covariance or Correlation Matrix Computation. Calculate the p × p symmetric sample covariance matrix S (or correlation matrix R for standardized data). Diagonal elements represent feature variances, while off-diagonal elements reflect pairwise associations. Analysts using spreadsheets often follow guidelines for generating a correlation matrix in Excel before running matrix decomposition.
  3. Step 3: Eigendecomposition or Singular Value Decomposition. Solve the characteristic determinant to extract eigenvalues and orthogonal eigenvectors. Each eigenvector specifies the direction of a principal component axis, while its eigenvalue quantifies the variance captured along that axis. Sort pairs in descending order: λ₁ ≥ λ₂ ≥ … ≥ λₚ.
  4. Step 4: Component Retention and Dimensionality Reduction. Evaluate explained variance ratios to determine how many components to keep. Retain components based on Kaiser’s rule (eigenvalues exceeding 1.0), scree plot elbow inflection, cumulative variance thresholds (typically 70% to 90%), or parallel analysis, discarding remaining noise dimensions.
  5. Step 5: Projection into Principal Component Scores. Assemble the p × k matrix Vk containing retained eigenvectors. Multiply centered data by Vk to compute n × k score matrix Yk = Xc Vk, representing observations in the reduced dimensional space.

This sequential workflow is widely referenced in scientific computing documentation and MIT OpenCourseWare computational thinking materials as the baseline linear dimension reduction framework.

Worked Example with Step-by-Step Arithmetic

To demonstrate the explicit arithmetic of PCA, consider a sample measuring two physiological variables across five subjects (n = 5, p = 2). Variable X₁ represents systolic recovery index, and Variable X₂ represents aerobic threshold score.

Subject Variable X₁ Variable X₂
Subject 1 7.0 9.0
Subject 2 9.0 7.0
Subject 3 10.0 10.0
Subject 4 11.0 13.0
Subject 5 13.0 11.0

Step 1: Compute Means and Center Data

Calculate variable sample means: x̄₁ = (7 + 9 + 10 + 11 + 13) / 5 = 10.0, and x̄₂ = (9 + 7 + 10 + 13 + 11) / 5 = 10.0. Subtracting column means yields centered matrix Xc:

  • Subject 1: [−3.0, −1.0]
  • Subject 2: [−1.0, −3.0]
  • Subject 3: [0.0, 0.0]
  • Subject 4: [+1.0, +3.0]
  • Subject 5: [+3.0, +1.0]

Step 2: Calculate Covariance Matrix

With degrees of freedom n − 1 = 4, calculate matrix entries:

s₁₁ = [ (−3.0)² + (−1.0)² + 0.0² + 1.0² + 3.0² ] / 4 = 20.0 / 4 = 5.0

s₂₂ = [ (−1.0)² + (−3.0)² + 0.0² + 3.0² + 1.0² ] / 4 = 20.0 / 4 = 5.0

s₁₂ = s₂₁ = [ (−3)(−1) + (−1)(−3) + (0)(0) + (1)(3) + (3)(1) ] / 4 = 12.0 / 4 = 3.0

Thus, sample covariance matrix S = [ [5.0, 3.0], [3.0, 5.0] ].

Step 3: Solve for Eigenvalues and Variance Explained

Solve the characteristic equation det(S − λ I) = 0:

det([ [5.0 − λ, 3.0], [3.0, 5.0 − λ] ]) = (5.0 − λ)² − 9.0 = 0 ⇒ (5.0 − λ) = ±3.0

This yields eigenvalues λ₁ = 5.0 + 3.0 = 8.0 and λ₂ = 5.0 − 3.0 = 2.0. Total variance is tr(S) = 5.0 + 5.0 = 10.0. Explained variance proportions are:

  • Component 1: λ₁ / Total = 8.0 / 10.0 = 0.80 (80.0%)
  • Component 2: λ₂ / Total = 2.0 / 10.0 = 0.20 (20.0%)

Step 4: Solve for Normalized Eigenvectors

For λ₁ = 8.0, solve (S − 8.0 I) v₁ = 0:

[ [−3.0, 3.0], [3.0, −3.0] ] [v₁₁, v₁₂]ᵀ = [0.0, 0.0]ᵀ ⇒ −3.0 v₁₁ + 3.0 v₁₂ = 0 ⇒ v₁₁ = v₁₂

With unit normalization v₁₁² + v₁₂² = 1, v₁₁ = v₁₂ = 1 / √2 ≈ 0.707107. Thus v₁ = [0.707107, 0.707107]ᵀ.

For λ₂ = 2.0, solve (S − 2.0 I) v₂ = 0:

[ [3.0, 3.0], [3.0, 3.0] ] [v₂₁, v₂₂]ᵀ = [0.0, 0.0]ᵀ ⇒ 3.0 v₂₁ + 3.0 v₂₂ = 0 ⇒ v₂₁ = −v₂₂

With unit normalization, v₂₁ = −1 / √2 ≈ −0.707107 and v₂₂ = 1 / √2 ≈ 0.707107. Thus v₂ = [−0.707107, 0.707107]ᵀ. Note v₁ᵀ v₂ = 0, verifying orthogonality.

Step 5: Compute Component Scores

Project centered rows onto eigenvectors using yki = xc,k1 v1i + xc,k2 v2i:

  • Subject 1: y₁₁ = −4 / √2 ≈ −2.8284; y₁₂ = 2 / √2 ≈ +1.4142
  • Subject 2: y₂₁ = −4 / √2 ≈ −2.8284; y₂₂ = −2 / √2 ≈ −1.4142
  • Subject 3: y₃₁ = 0.0000; y₃₂ = 0.0000
  • Subject 4: y₄₁ = 4 / √2 ≈ +2.8284; y₄₂ = 2 / √2 ≈ +1.4142
  • Subject 5: y₅₁ = 4 / √2 ≈ +2.8284; y₅₂ = −2 / √2 ≈ −1.4142

Sample score variances equal Var(y₁) = [ 2(−2.8284)² + 0² + 2(2.8284)² ] / 4 = 8.0 and Var(y₂) = 2.0, matching eigenvalues exactly with zero covariance.

Interpreting Principal Components: Loadings, Scores, and Reading Guidance

Interpreting PCA results requires distinguishing eigenvectors from component loadings. Eigenvectors establish axis directions in geometric space. Component loadings quantify Pearson correlations between original variables and component scores: lji = vji × (√λi / sj). For standardized variables, lji = vji √λi.

Loadings span from −1.0 to +1.0. Variables exhibiting high absolute loadings govern component substantive identity. Analysts evaluate relationships by reading principal component biplots and scree plots, assessing vector angles to gauge correlation and observation projections to evaluate relative subject positions.

The table below summarizes reading guidance across PCA diagnostics.

Diagnostic Metric Numerical Condition Substantive Meaning Recommended Action
Eigenvalue (λi) λ ≥ 1.0 (on correlation matrix) Captures more variance than a single standardized original variable. Retain component under Kaiser’s criterion.
Eigenvalue (λi) λ under 0.70 Captures less variance than individual features, indicating noise. Discard unless required by domain theory.
Component Loading (|lji|) |l| ≥ 0.50 to 0.70 Strong linear relationship between feature and component axis. Use variable construct to label the component.
Component Loading (|lji|) |l| under 0.30 Negligible association with component axis. Suppress from factor interpretation tables.
Cumulative Variance 70% to 90% Sufficient total system variance retained in reduced space. Conclude component extraction.
Observation Score (yki) Score exceeding +2.0 SD Subject displays high values on features with positive loadings. Flag as distinct high-magnitude observation.
Observation Score (yki) Score within ±0.5 SD Subject sits near the multivariate sample mean. Interpret as typical baseline observation.

Assumptions, Diagnostics, and Common Mistakes

While PCA is non-parametric, its geometric efficacy relies on several data conditions:

  • Linearity: PCA constructs linear feature combinations. Non-linear associations distort component orientations, requiring kernel PCA or manifold learning instead.
  • Continuous Variables: PCA assumes continuous interval or ratio features. Categorical variables should be analyzed using correspondence analysis or polychoric PCA.
  • Sample Size: Reliable covariance estimation requires an observation-to-variable ratio of at least 5:1, with an absolute minimum sample of 50 to 100 observations.
  • Absence of Outliers: Because covariances square deviation distances, extreme outliers pull principal component axes toward anomalous observations.
  • Matrix Factorability: Before extraction, verify Bartlett’s test of sphericity and Kaiser-Meyer-Olkin sampling adequacy, requiring KMO values above 0.60.

Common analytical mistakes in applied research include:

  1. Omitting Feature Standardization: Unstandardized variables with large numerical magnitudes dominate the covariance matrix regardless of informational value.
  2. Confusing PCA with Factor Analysis: PCA decomposes total variance into descriptive composites. In contrast, researchers consult exploratory factor analysis guidelines when modeling unobserved latent constructs that explain shared common covariance while isolating unique error variance.
  3. Rotating PCA Components: Applying orthogonal rotations (such as Varimax) destroys the sequential variance-maximizing property of PCA.
  4. Treating PCA as Feature Selection: PCA forms linear composites of all features rather than selecting individual variables to retain. Variable selection requires penalized regression methods.
  5. Neglecting Multicollinearity: Running regression on collinear predictors yields unstable estimates. Researchers resolve this through principal component regression for multicollinearity, using orthogonal scores as regression predictors.

How to Report PCA Results in APA Style

Reporting PCA in American Psychological Association (APA 7th edition) style requires documenting sampling adequacy, extraction rules, eigenvalues, variance percentages, and component loadings.

Narrative Reporting Example

A standard APA results section reads as follows:

A principal component analysis was conducted on the 10 cognitive assessment items (N = 200) using the sample correlation matrix. The Kaiser-Meyer-Olkin measure of sampling adequacy was .81, verifying sampling adequacy for extraction. Bartlett’s test of sphericity was statistically significant, χ²(45) = 612.45, p under .001, confirming correlation matrix factorability.

Initial eigenvalues indicated that the first two components accounted for 48.2% and 21.4% of total variance, respectively, for a cumulative total of 69.6%. The third component yielded an eigenvalue of 0.82 (8.2% of variance). Visual inspection of Cattell’s scree plot revealed an elbow after the second component. Horn’s parallel analysis confirmed that only the first two empirical eigenvalues exceeded 95th percentile eigenvalues from synthetic random matrices. Consequently, two principal components were retained. Component loadings are presented in Table 1.

APA Style Loading Table

APA tables display retained loadings with horizontal rules, suppressing loadings below .30.

Assessment Variable Component 1 Component 2
Processing speed index .82 .11
Working memory capacity .79 .18
Executive function task .75 −.14
Affective regulation score .08 .84
Stress response index −.12 .79
Eigenvalue (λ) 4.82 2.14
% of Variance Explained 48.2% 21.4%
Cumulative % Variance 48.2% 69.6%

Software Implementation: Excel, R, and Python

Executing PCA across standard software tools automates matrix calculations while adhering to the five procedural steps. Below are verified scripts for Excel, R, and Python.

1. Microsoft Excel

In Excel, calculate column averages using =AVERAGE(A2:A6). Compute centered columns via =A2-$A$7. Compute sample covariance using =COVARIANCE.S(range1, range2). Once eigenvectors are obtained, project observation scores using matrix multiplication array formula =MMULT(centered_data, eigenvector_range).

2. R (prcomp)

In R, the standard function is prcomp(), which employs Singular Value Decomposition. Researchers can review further details on running prcomp for PCA in R:

data_mat = data.frame(
  X1 = c(7, 9, 10, 11, 13),
  X2 = c(9, 7, 10, 13, 11)
)

pca_output = prcomp(data_mat, center = TRUE, scale. = FALSE)
summary(pca_output)
pca_output$rotation
pca_output$x
eigenvalues = pca_output$sdev^2
print(eigenvalues)

3. Python (scikit-learn)

In Python, scikit-learn provides optimized decomposition routines. Analysts often configure a scikit-learn pipeline for PCA in Python combining scaling and component extraction:

import numpy as np
from sklearn.decomposition import PCA

X = np.array([
    [7.0, 9.0],
    [9.0, 7.0],
    [10.0, 10.0],
    [11.0, 13.0],
    [13.0, 11.0]
])

pca = PCA(n_components=2)
scores = pca.fit_transform(X)

print("Explained variance:", pca.explained_variance_)
print("Explained variance ratio:", pca.explained_variance_ratio_)
print("Components (eigenvectors):
", pca.components_)
print("Component scores:
", scores)

Frequently asked questions

What is Principal Component Analysis (PCA) and how does it work?

Principal component analysis is an unsupervised statistical technique that reduces the dimensionality of large datasets containing correlated variables into a smaller set of uncorrelated variables called principal components. It works by computing the covariance or correlation matrix of mean-centered data and extracting its eigenvalues and eigenvectors. The eigenvectors define orthogonal coordinate axes, while eigenvalues represent the variance captured along each axis.

What is the difference between PCA and Factor Analysis?

PCA and exploratory factor analysis share variable-reduction goals but have distinct mathematical foundations. PCA is an empirical linear transformation that decomposes total variance into orthogonal composites without assuming latent variables. In contrast, factor analysis assumes observed variables reflect unobserved latent factors and models shared common covariance while isolating unique error variance.

Why is PCA used in machine learning?

In machine learning workflows, PCA combats the curse of dimensionality, eliminates multicollinearity among features, accelerates model training time, and mitigates overfitting. By converting high-dimensional feature spaces into compact, uncorrelated component scores, PCA provides robust, low-dimensional inputs for clustering, regression, and visualization.

How do you choose the number of principal components?

Researchers use multiple empirical criteria to choose retained components. Common methods include Kaiser’s criterion (retaining eigenvalues greater than 1.0 on correlation matrices), Cattell’s scree plot test (locating the curve inflection point or elbow), setting cumulative variance thresholds (such as 70% to 90%), and Horn’s parallel analysis (retaining empirical eigenvalues exceeding synthetic random thresholds).

Do you need to scale or standardize data before PCA?

Yes, standardizing data is necessary whenever variables are measured in different units or exhibit substantially different numerical scales. Because PCA maximizes variance, variables with large absolute ranges will dominate covariance calculations and determine leading principal components regardless of informational relevance. Standardizing features to zero mean and unit variance ensures equal weighting.

Sources

Data: Dimensionality Reduction Decision and Component Retention Benchmark Matrix

Comparison of component retention criteria, mathematical thresholds, and primary software defaults across statistical frameworks, compiled from NIST e-Handbook Section 6.5.5, R stats package documentation, and scikit-learn decomposition specifications.

Dimensionality Reduction Decision and Component Retention Benchmark Matrix
Retention CriterionMathematical BasisDefault Threshold (criterion value)Software ImplementationPrimary Failure Mode
Kaiser-Guttman RuleEigenvalues of correlation matrix exceeding mean eigenvalue1SPSS FACTOR default / R psychTends to over-extract components when variable count p > 30
Cattell Scree TestVisual inflection point identifying elbow before debris asymptote0R stats screeplot / Stata screeSubjective interpretation when multiple subtle elbows appear
Cumulative Variance ExplainedRatio of cumulative sum of retained eigenvalues to total trace80scikit-learn PCA(n_components=0.80)Arbitrary threshold dependent on domain and signal-to-noise ratio
Horn Parallel AnalysisEmpirical eigenvalue exceeding 95th percentile of synthetic random matrices0.95R paran / Python paranComputationally intensive with large sample sizes and wide matrices
Minka MLEProbabilistic PCA maximizing marginal likelihood of spherical covariance0scikit-learn PCA(n_components='mle')Assumes isotropic Gaussian noise and linear latent generative model

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about Principal Component Analysis Steps: Math, Example, and Code

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →