PCA in R, code examples on using prcomp and princomp in R

I have used several times PCA in R and get always confused about the use of prcomp and princomp in R.

The following code in R compares both methods and the usual tasks done with both:

############################################################
# PCA IN R
# example on using prcomp and princomp in R
# Look at this blogs and webs:
# http://stats.stackexchange.com/questions/104306/what-is-the-difference-between-loadings-and-correlation-loadings-in-pca-and
# http://www.sthda.com/english/wiki/principal-component-analysis-in-r-prcomp-vs-princomp-r-software-and-data-mining
#
# prcomp is preferred, see: http://stats.stackexchange.com/questions/20101/what-is-the-difference-between-r-functions-prcomp-and-princomp

############################################################
# OBTAIN PRINCIPAL COMPONENTS
data(mtcars)
pc1 = prcomp(mtcars, center=TRUE, scale=TRUE)$x[,1:2] #principal components scaled, mean subtracted
pc1
pc2 = prcomp(mtcars,center= TRUE, scale= FALSE)$x[,1:2] #principal components not scaled, not mean subtracted
pc2
pc3= princomp(mtcars)$score[,1:2] # principal components, same value as: prcomp(mtcars,center= TRUE, scale= FALSE)$x[,1:2], with a possible sign change
pc3

############################################################
# OBTAIN LOADINGS
load1= prcomp(mtcars)$rot[,1:2]
load1
load2= princomp(mtcars)$loadings[,1:2] # same value as: prcomp(mtcars)$rot[,1:2], , with a possible sign change
load2

############################################################
# OBTAIN ORIGINAL DATA
mtcars
mtcars_2=prcomp(mtcars)$x %*% t(prcomp(mtcars)$rot)
mtcars_2 # not the same as mtcars
mtcars_3=princomp(mtcars)$score %*% t(princomp(mtcars)$loadings)
mtcars_3 # not the same as mtcars
mtcars_2_c=prcomp(mtcars)$x %*% t(prcomp(mtcars)$rotation)+matrix(rep(prcomp(mtcars)$center,each=nrow(mtcars)),nrow=nrow(mtcars))
mtcars_2_c # after adding the mean substracted previously, the result is the same as mtcars
mtcars_3_c=princomp(mtcars)$score %*% t(princomp(mtcars)$loadings)+matrix(rep(princomp(mtcars)$center,each=nrow(mtcars)),nrow=nrow(mtcars))
mtcars_3_c # same as mtcars
#in case of using scaling it is needed to multiply by the scale factor: http://stackoverflow.com/questions/29783790/how-to-reverse-pca-in-prcomp-to-get-original-data

Anuncios