factpca<-function(x){ #Performs Principal Components Factor Analysis on x# #using the correlation matrix. #It returns the un-rotated loadings.# xeig<-eigen(cor(x)) xval<-xeig$values xvec<-xeig$vectors for (i in 1:length(xval)){ xvec[,i]<-xvec[,i]*sqrt(xval[i])} rownames(xvec)<-colnames(x) return(xvec) } factpf<-function(x){ #Performs Principal Factor Factor Analysis on x# #using the correlation matrix. #It returns the un-rotated loadings.# n<-ncol(x) redcormat<-cor(x) diag(redcormat)<-apply(abs(cor(x)-diag(1,nrow=n,ncol=n)),2,max) xeig<-eigen(redcormat) xval<-xeig$values xvec<-xeig$vectors for (i in 1:length(xval[xval>0])){ xvec[,i]<-xvec[,i]*sqrt(xval[i])} rownames(xvec)<-colnames(x) return(xvec[,xval>0]) } factiter<-function(x,niter=10,maxfactors=ncol(x)){ #Performs Iterated Principal Factor Factor Analysis on x# #using the correlation matrix.# #It returns the communalties after each iteration# #and the final un-rotated loadings.# n<-ncol(x) temp<-matrix(0,nrow=n,ncol=n) comm<-matrix(0,nrow=niter+1,ncol=n) y<-factpf(x) m<-ncol(y) temp[1:n,1:m]<-y comm[1,]<-apply(temp^2,1,sum) for (i in 2:(niter+1)){ redcormat<-cor(x) diag(redcormat)<-comm[i-1,] xeig<-eigen(redcormat) m<-min(maxfactors,length(xeig$values[xeig$values>0])) for (j in 1:m){ xeig$vectors[,j]<-xeig$vectors[,j]*sqrt(xeig$values[j])} temp[1:n,1:m]<-xeig$vectors[1:n,1:m] comm[i,]<-apply(temp[1:n,1:m]^2,1,sum) } f.loadings<-temp[1:n,1:m] rownames(f.loadings)<-colnames(x) return(comm,f.loadings) } testfit<-function(x,loadings){ #Returns the estimated Cov(error) matrix# error<-cor(x)-loadings%*%t(loadings) return(round(error,4))} fitsummary<-function(x,loadings){ #Returns the estimated Var(error), a summary of # #the covariances of the errors, and the estimated# #communalities# error<-cor(x)-loadings%*%t(loadings) errorvar<-round(diag(error),4) errorcov<-round(summary(error[upper.tri(error)]),4) communality<-round(apply(loadings^2,1,sum),4) return(errorvar,errorcov,communality)}