For W 11/1

# SOCY7113 A PCA example

# We'll be using tools from the psych library.
library(psych)

# We'll use an example from the ANES2012.
ANES2012<-read.csv("http://www.courseserve.info/files/ANES2012r.csv")
attach(ANES2012)

# First iteration of the PCA
ANESpca<-subset(ANES2012, select=c("ftgr_xfund","ftgr_catholics","ftgr_feminists","ftgr_liberals","ftgr_middle","ftgr_unions","ftgr_poor", "ftgr_bigbus","ftgr_welfare","ftgr_cons","ftgr_working","ftgr_gay","ftgr_rich","ftgr_muslims","ftgr_xian","ftgr_atheists","ftgr_mormons","ftgr_tea"))
pca1<-principal(ANESpca,nfactors=18,rotate="none",scores=F)
plot(pca1$values, type="b")

# We make a decision about the number of factors to retain
# and repeat the PCA.
pca2<-principal(ANESpca,nfactors=5,rotate="varimax",scores=T)

# The hard part is the interpretation of the "factors"
print.psych(pca2, cut=0.45, sort=T)

# Because we saved the factor scores, we can use them as variables in other analysis
# such as IVs in a linear model.
ANES2012pca2<-cbind(ANES2012,pca2$scores)

# Let's use the factor scores to predict party affiliation:
summary(lm(V161158x~PC1+PC2+PC3+PC4+PC5))