Skip to content

Instantly share code, notes, and snippets.

@m-Py
Created February 22, 2024 11:54
Show Gist options
  • Select an option

  • Save m-Py/dc12351dfc602417110940e9cb4200f8 to your computer and use it in GitHub Desktop.

Select an option

Save m-Py/dc12351dfc602417110940e9cb4200f8 to your computer and use it in GitHub Desktop.

Revisions

  1. m-Py created this gist Feb 22, 2024.
    22 changes: 22 additions & 0 deletions PCA_Variance_Explained.R
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    # 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