# R in Action (2nd ed): Chapter 14 # Principal components and factor analysis # requires package psych # install.packages(c("psych")) #------------------------------ par(ask=TRUE) set.seed(1234) # make results reproducible ## Principal components analysis of US Judge Ratings library(psych) fa.parallel(USJudgeRatings[,-1], fa="pc", ntrials=100, show.legend=FALSE, main="Scree plot with parallel analysis") pc <- principal(USJudgeRatings[,-1], nfactors=1, score=TRUE) pc # principal components scores head(pc$scores) # correlation between PC score and number of lawyer contacts cor(USJudgeRatings$CONT, pc$score) ## Principal components analysis Harman23.cor data library(psych) fa.parallel(Harman23.cor$cov, n.obs=302, fa="pc", ntrials=100, show.legend=FALSE, main="Scree plot with parallel analysis") pc <- principal(Harman23.cor$cov, nfactors=2, rotate="none") pc # varimax rotation rc <- principal(Harman23.cor$cov, nfactors=2, rotate="varimax") rc # principal components scoring coefficients round(unclass(rc$weights), 2) ## Exploratory factor analysis of ability.cov data options(digits=2) library(psych) covariances <- ability.cov$cov # convert covariances to correlations correlations <- cov2cor(covariances) correlations # determine number of factors to extract fa.parallel(correlations, n.obs=112, fa="both", ntrials=100, main="Scree plots with parallel analysis") # principal axis factoring without rotation fa <- fa(correlations, nfactors=2, rotate="none", fm="pa") fa # factor extraction with orthogonal rotation fa.varimax <- fa(correlations, nfactors=2, rotate="varimax", fm="pa") fa.varimax # factor extraction with oblique rotation fa.promax <- fa(correlations, nfactors=2, rotate="promax", fm="pa") fa.promax # calculate factor loading matrix P <- unclass(fa.promax$loading) F <- P %*% fa.promax$Phi colnames(F) <- c("PA1", "PA2") F # plot factor solution factor.plot(fa.promax, labels=rownames(fa.promax$loadings)) fa.diagram(fa.promax, simple=FALSE)