PCA in R: Analyze USArrests Data and Choose Principal Components

Jun 20, 2026 645 views

PCA in R: Start With the Result, Then Check the Choices

The headline result is striking: on R’s USArrests dataset, two principal components account for 86.75% of the total variance. That makes a two dimensional summary plausible, but it doesn’t settle how many components you should keep. The Kaiser rule, for example, rejects the second component even though it explains nearly a quarter of the variance and represents urbanization. The disagreement is the useful lesson: component selection calls for judgment, not a single cutoff.

You can run the analysis with base R’s prcomp() function:

pca <- prcomp(data, scale = TRUE)
summary(pca)

prcomp() centers and scales the variables when requested, then uses singular value decomposition (SVD) to calculate the components. Its output includes variable loadings in pca$rotation and observation scores in pca$x. Those are the building blocks for interpreting and plotting the results.

Here’s a compact script using USArrests. It checks the data, runs PCA, compares component selection methods, and produces biplots:

📋 Complete Code — Copy, Paste, Run

# Complete PCA in R script -- copy, paste, run top to bottom
# 1. Install and load required packages
install.packages(c("ggplot2", "factoextra"))
library(ggplot2)
library(factoextra)

#2. Load the data and check assumptions
data(USArrests)
str(USArrests)
cor(USArrests)
apply(USArrests, 2, shapiro.test)

#3. Scale the data (prcomp() can also do this inline with scale = TRUE)
data_scaled <- scale(USArrests)
head(data_scaled)

#4. Run PCA
pca <- prcomp(USArrests, scale = TRUE)
summary(pca)
pca$rotation

#5. Decide how many components to keep
plot(pca$sdev^2, type = "b", xlab = "Principal Component", ylab = "Eigenvalue", main = "Scree Plot")
fviz_eig(pca, addlabels = TRUE, barfill = "steelblue", barcolor = "steelblue",
linecolor = "firebrick", main = "Scree Plot: Variance Explained by Component")
pve <- pca$sdev^2 / sum(pca$sdev^2)
cum_pve <- cumsum(pve)
plot(cum_pve, type = "b", xlab = "Principal Component",
ylab = "Cumulative Proportion of Variance Explained")

#6. Visualize results
biplot(pca, scale = 0)
fviz_pca_biplot(pca,
geom.ind = "point",
col.ind = as.factor(state.region),
palette = "jco",
addEllipses = TRUE,
col.var = "black",
repel = TRUE,
legend.title = "Region") +
theme_minimal()

Jump to the full step-by-step explanation ↓

What PCA Reveals—and What It Leaves to Decide

  • PCA replaces correlated variables with fewer uncorrelated principal components that preserve as much of the original variance as possible.
  • In R, prcomp() is generally preferred to the older princomp() because its SVD approach is more numerically stable.
  • For USArrests, the first two components explain 86.75% of total variance, according to the R output shown in the tutorial.
  • A scree plot, the Kaiser rule (retain eigenvalues above 1), and a cumulative variance threshold can point to different answers. This dataset makes that tension visible.
  • PCA and Factor Analysis answer different questions; the tutorial compares when each is appropriate.

PCA in R step-by-step tutorial using prcomp and ggplot2

If your dataset contains many correlated variables, PCA can help compress them into a smaller set of axes and make broad patterns easier to inspect in two dimensions. That doesn’t mean the discarded dimensions never matter; it means you’re choosing a summary that retains most of the variation for a particular analysis.

The tutorial’s author, Dr Zubair Goraya, says he has a PhD-level background in statistics and several years of experience using R in statistical consulting and research. He describes encountering the same practical questions—how many components to retain, how to read prcomp() output, and how to create a ggplot2 biplot—in his own research, and later helping thesis and dissertation students work through them.

What the Components Mean

PCA is a dimensionality reduction method. It turns correlated variables into new, mutually uncorrelated variables called principal components. The first component captures the greatest possible share of variance; each following component captures as much as it can from what remains, while staying orthogonal to the earlier ones.

When to use PCA in R for dimensionality reduction

How PCA Works Under the Hood

You don’t need to calculate the steps yourself, but knowing what prcomp() is doing makes its output easier to interpret:

  1. Standardize each variable to mean 0 and standard deviation 1, so differences in measurement units don’t drive the result.
  2. Calculate the covariance matrix, which describes how pairs of variables vary together.
  3. Find the eigenvectors, which define component directions, and eigenvalues, which measure the variance along those directions. The largest eigenvalue belongs to PC1.
  4. Project the observations onto the new axes to get component scores: each observation’s coordinates in the reduced space.

prcomp() reaches this result through SVD rather than directly decomposing the covariance matrix. That route is numerically more stable and is the reason it’s usually favored over princomp() in R.

Data and Packages

PCA is intended for numeric, continuous variables. The tutorial uses three packages or functions:

  • prcomp(), included in base R’s stats package.
  • ggplot2, for custom scree plots and biplots.
  • factoextra, which wraps PCA results in convenient plotting functions built on ggplot2.
install.packages(c("ggplot2", "factoextra"))
library(ggplot2)
library(factoextra)

USArrests is built into R. It records violent crime rates and the percentage of the population living in urban areas across all 50 US states in 1973. It’s also used in An Introduction to Statistical Learning, making it possible to compare results with a familiar reference.

Check the Data Before Running PCA

The tutorial checks that the variables are numeric, related, and reasonably close to normally distributed:

data(USArrests)
str(USArrests) # numeric and continuous?
cor(USArrests) # linearly related?
apply(USArrests, 2, shapiro.test) # normally distributed?

The reported Shapiro–Wilk results show UrbanPop as the only variable that does not significantly depart from normality, with p = 0.977. The table gives these results:

VariableWp-valueSignificant?
Murder0.9570.067Yes
Assault0.9520.041Yes
UrbanPop0.9770.439No
Rape0.9470.025Yes

There’s an inconsistency in the source’s description: it gives UrbanPop a p-value of 0.977 in the prose, while the table reports 0.439. Both are above 0.05, so the stated conclusion is unchanged, but the exact value needs checking. The tutorial proceeds with all four variables, arguing that PCA can tolerate mild non-normality at a sample size of 50. For stronger departures, it suggests considering a transformation or reconsidering PCA, with a comparison to Factor Analysis.

Scale the Variables, Then Run PCA

Murder, Assault, and Rape are rates per 100,000 residents; UrbanPop is a percentage. Without scaling, Assault—which reaches 337—could dominate because of its numeric range. Setting scale = TRUE handles this inside prcomp(). To inspect standardized values first, you can also normalize the data manually with Z-score standardization:

data_scaled <- scale(USArrests)
head(data_scaled)

Then run PCA on all four variables:

pca <- prcomp(USArrests, scale = TRUE)
summary(pca)

The reported summary is:

Importance of componentsPC1PC2PC3PC4
Standard deviation1.57490.99490.59710.4164
Proportion of Variance0.62010.24740.08910.0434
Cumulative Proportion0.62010.86750.95661.0000

PC1 accounts for 62.0% of the variance; PC1 and PC2 together account for 86.75%. The loadings help explain why. PC1 has strong negative loadings on Murder (-0.536), Assault (-0.583), and Rape (-0.543), with a smaller loading on UrbanPop (-0.278). It can be read as an overall violent crime axis. PC2 loads mainly on UrbanPop (0.873), making it an urbanization axis largely separate from crime rates.

Choosing How Many Components to Keep

No single retention rule works in every case. The tutorial uses three methods, and the fact that they don’t all agree on USArrests is a reminder to interpret the outputs rather than follow a threshold blindly.

Read the Scree Plot

plot(pca$sdev^2, type = "b", xlab = "Principal Component", ylab = "Eigenvalue", main = "Scree Plot")

Scree plot of PCA eigenvalues in R showing the elbow point

Look for the “elbow,” where the curve starts to flatten. Components before that point tend to add more information than those that follow.

Make a Scree Plot With ggplot2

For a plot based on ggplot2 rather than base R graphics, factoextra provides fviz_eig():

fviz_eig(pca, addlabels = TRUE, barfill = "steelblue", barcolor = "steelblue",
linecolor = "firebrick", main = "Scree Plot: Variance Explained by Component")

The function returns a ggplot object, so you can add themes, labels, and palettes as you would to other ggplot2 charts.

Apply the Kaiser Rule

The Kaiser rule retains components whose eigenvalues exceed 1. Here, only PC1 clears that bar:

ComponentEigenvalueKeep under Kaiser rule?
PC12.480Yes
PC20.990No (just under 1)
PC30.357No
PC40.173No

That cutoff would discard PC2 at 0.990, a hair below 1, despite its nearly 25% share of variance and clear urbanization interpretation. This is a weak case for treating the Kaiser rule as decisive. The second component looks useful on the evidence presented.

Check Cumulative Variance

pve <- pca$sdev^2 / sum(pca$sdev^2)
cum_pve <- cumsum(pve)
plot(cum_pve, type = "b", xlab = "Principal Component",
ylab = "Cumulative Proportion of Variance Explained")

Cumulative proportion of variance explained by each PCA component in R

A common target is 80–90% cumulative variance. Two components reach 86.75%, making PC1 and PC2 the strongest choice across the three methods described.

Plot the PCA Results

A biplot puts observations and variable loadings on the same PC1/PC2 axes. The base R version is simple:

biplot(pca, scale = 0)

Base R biplot of PCA loadings and scores for USArrests data

For a more configurable plot, factoextra can color observations, add confidence ellipses, and move labels to reduce overlap. The example colors states by region:

fviz_pca_biplot(pca,
geom.ind = "point",
col.ind = as.factor(state.region),
palette = "jco",
addEllipses = TRUE,
col.var = "black",
repel = TRUE,
legend.title = "Region") +
theme_minimal()

fviz_pca_biplot() also returns a ggplot object, so you can change the palette, add a title with + labs(title = "..."), or adjust the theme without changing the PCA calculation.

ggplot2 PCA biplot with confidence ellipses by US region

The regional pattern in the biplot matches the loadings: Southern states sit toward higher PC1 scores, associated here with more violent crime, while Western states vary more along PC2, the axis linked to urbanization. That’s a useful check that the component interpretation carries through to the observations.

PCA and factor analysis answer different questions

PCA and factor analysis both compress many measurements into fewer dimensions, but they describe different things. PCA is a data reduction method: it captures as much total variance as possible. Factor analysis models shared variance to estimate latent constructs that may explain why observed measures move together. Treating them as interchangeable can leave a thesis methodologically misaligned with its research question.

PCAFactor Analysis
PurposeReduce dimensions by maximizing explained varianceEstimate latent constructs behind observed variables
Variance includedTotal variance, including common and unique varianceCommon variance; unique and error variance are separated
Latent variable assumptionNone; a mathematical transformation of the dataObserved variables reflect underlying factors
RotationUsually not usedOften used for interpretation, such as varimax or promax
R functionsprcomp()factanal() or psych::fa()
Best suited toDimension reduction or visualizationTesting a theory about constructs measured by items

If your survey is meant to measure anxiety, job satisfaction, or brand loyalty, Exploratory Factor Analysis is generally the more fitting choice. Similar-looking input data don’t make the methods equivalent.

Reporting the analysis

A formal report should show how you chose the number of components, not just state the final answer. Include a loadings table and a scree plot or cumulative variance plot so readers can assess that decision. The example below uses the USArrests results from the preceding steps:

Example wording:
“A principal component analysis (PCA) was performed on Murder, Assault, UrbanPop, and Rape using R’s prcomp() function (R Core Team). Variables were standardized before analysis. The Kaiser criterion (eigenvalue > 1), scree plot, and an 80% cumulative variance threshold were considered together, and two components were retained. PC1 accounted for 62.0% of the variance and was driven mainly by Murder, Assault, and Rape, with loadings of -0.54, -0.58, and -0.54, respectively. This component was interpreted as a general violent crime dimension. PC2 explained a further 24.7% and loaded almost entirely on UrbanPop (0.87), consistent with an urbanization dimension. Combined, the two components explained 86.75% of the total variance.”

These results give the components an interpretable shape, but the retention decision still needs evidence on the page. A linked reference on how to count appears in the original material; the practical reporting guidance here is to provide the loadings and variance plots alongside the write-up.

Where component scores can go next

The scores stored in pca$x can serve as inputs to later analyses. You might use them for k-means clustering on a reduced, decorrelated feature set, or examine multicollinearity before fitting a regression model. PCA can make downstream work easier to manage, though the components still need to make sense for the question you’re asking.

Practical questions about PCA in R

Which R package should I use? For most analyses, base R’s prcomp() is enough and is generally preferred to princomp() for numerical accuracy. Add factoextra for richer plots. For broader multivariate exploratory methods, including correspondence analysis, consider FactoMineR.

How can I plot the results? Use plot(pca) for a scree plot, biplot(pca) for a base R display of scores and loadings, or factoextra::fviz_pca_biplot(pca) for a customizable ggplot2 plot with labels, color, and ellipses.

What does prcomp() return? Its object contains sdev (component standard deviations), rotation (the loadings matrix), x (observation scores), and center and scale (the values used to center and scale the data).

How do prcomp() and princomp() differ? princomp() uses eigen decomposition of the covariance matrix. prcomp() applies singular value decomposition (SVD) directly to the data matrix, which has slightly better numerical accuracy; R’s documentation recommends it.

How many components should I keep? There’s no single cutoff that works for every dataset. Compare the scree plot elbow, the Kaiser rule (eigenvalue > 1), and a cumulative variance target, often 80–90%. As the earlier example shows, these criteria can disagree, so use judgment rather than treating any one rule as decisive.

Can PCA handle categorical variables? Standard PCA expects numeric, continuous inputs. For categorical data, use Multiple Correspondence Analysis (MCA), available as FactoMineR::MCA(). It applies dimensionality reduction to category frequencies in a contingency table. For background on categorical data, see the linked guide.

What mistakes should I watch for? First, omitting scale = TRUE can let variables with larger units dominate PC1. Second, missing values and outliers can distort the covariance structure. Third, a misread scree plot or ignored loading signs can lead to a weak interpretation.

Where is PCA used? Common applications include image compression, facial recognition feature extraction, gene expression analysis in bioinformatics, customer segmentation, and preprocessing before clustering or regression to remove multicollinearity.

From output to a defensible interpretation

The workflow in this guide covers scaling, fitting prcomp(), selecting components with multiple criteria, plotting results in base R and ggplot2, and reporting the analysis. You can apply the same steps to your own data by replacing USArrests with your data frame. The harder part is deciding whether PCA answers your research question at all—and explaining that choice clearly.

If you’re working through PCA, factor analysis, or another multivariate method for a thesis or dissertation and want feedback on your output, you can request PCA or statistics help on WhatsApp or join the community.

For comments on the original article, visit RStudioDataLab. R-bloggers.com offers daily email updates on R news and tutorials about learning R. For R and data science jobs, visit R-users. To share a blog on R-bloggers, submit it here, or use R-posts.

Continue reading: PCA in R: Principal Component Analysis Step-by-Step (prcomp + ggplot2)

Source: Unknown · www.r-bloggers.com

Comments

Sign in to comment.
No comments yet. Be the first to comment.

Related Articles

PCA in R: Principal Component Analysis Step-by-Step (prco...