Skip to content

Instantly share code, notes, and snippets.

@m-Py
Created February 22, 2024 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m-Py/dc12351dfc602417110940e9cb4200f8 to your computer and use it in GitHub Desktop.
Save m-Py/dc12351dfc602417110940e9cb4200f8 to your computer and use it in GitHub Desktop.
Get % of variance explained by Principal Component Analysis
# Get % of variance explained by Principal Component Analysis
library(psych)
pca_variance_explained <- function(data, n_components) {
pca <- psych::principal(data, n_components, rotate = "none")
list(
by_variable = colSums(cor(pca$scores, data)^2),
total = summary(prcomp(data))$importance["Cumulative Proportion", paste0("PC", n_components)]
)
}
# Example
data <- iris[, -5]
n_components <- 2
pca_variance_explained(data, n_components)
#> $by_variable
#> Sepal.Length Sepal.Width Petal.Length Petal.Width
#> 0.9225986 0.9909193 0.9837300 0.9352804
#>
#> $total
#> [1] 0.97769
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment