Created
February 24, 2020 18:38
-
-
Save martinctc/6c46fbec5288e642fb47e9e5fa767722 to your computer and use it in GitHub Desktop.
[Varimax rotated PCA in R] #R
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
library(tidyverse) | |
library(FactoMineR) | |
iris %>% | |
select(-Species) %>% | |
PCA(graph = FALSE) -> res | |
# FactoMineR does not return the loadings but the coordinates of the variables | |
# You can divide the results of PCA by the square root of the eigenvalue of each dimension to recover the loadings | |
# rotation - method 0 | |
# In ugly base code | |
t(apply(res$var$coord, 1, function(x) {x/sqrt(res$eig[,1])})) | |
# wrapped in a function | |
rotate_varimax <- function(x){ | |
mini <- function(y){ | |
y / sqrt(x$eig[,1]) | |
} | |
x %>% | |
.$var %>% | |
.$coord %>% # coordinates of variables to create a scatter plot | |
apply(1, mini) %>% | |
t() | |
} | |
res %>% rotate_varimax() # returns loadings? | |
# return loadings | |
sweep(res$var$coord, 2, sqrt(res$eig[,1]),'/') | |
## method 2 | |
## same result | |
iris %>% | |
select(-Species) %>% | |
prcomp(scale = TRUE) %>% | |
.$rotation | |
iris %>% | |
select(-Species) %>% | |
prcomp(scale = TRUE) -> p | |
p$x | |
iris %>% | |
select(-Species) %>% | |
psych::principal(nfactors = 3, rotate = "varimax") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment