Created
February 22, 2024 11:54
-
-
Save m-Py/dc12351dfc602417110940e9cb4200f8 to your computer and use it in GitHub Desktop.
Get % of variance explained by Principal Component Analysis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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