# Perform PCA on exams data exams<-matrix(scan(file='exams.txt'),byrow=T,ncol=5) nr<-length(exams[,1]) dimnames(exams)<-list(1:nr,c("X1","X2","X3","X4","X5")) exams.prc<-princomp(exams,cor=F) # cor=F (the default) means use covariances not correlations print(summary(exams.prc,loadings=T)) # Plot of PC variances plot(exams.prc) # Draw a screeplot with lines screeplot(exams.prc,type='lines') # Apply Kaiser's criterion by first computing mean eigenvalue exams.eigen<-exams.prc$sdev^2 print(sqrt(mean(exams.eigen))) # Plot prediction scores of original data pr<-predict(exams.prc) plot(1:88,pr[,1],xlab='Student',ylab='Component 1') plot(1:88,pr[,2],xlab='Student',ylab='Component 2') plot(1:88,pr[,3],xlab='Student',ylab='Component 3') plot(1:88,pr[,4],xlab='Student',ylab='Component 4') # Print prediction scores for new data exam2<-matrix(scan(file='exam2.txt'),byrow=T,ncol=5) dimnames(exam2)<-list(1:6,c("X1","X2","X3","X4","X5")) print(predict(exams.prc,newdata=exam2)) # Biplot biplot(exams.prc)