Principal Component Analysis in R
There are, at least :), two ways to compute the principal component analysis of a data set in R. The first one is from scratch computing eigenvectors and eigenvalues. It works as follows
#
# From scratch
#
cbind(1:10,1:10 + 0.25*rnorm(10)) -> myData
myData - apply(myData,2,mean) -> myDataZM
cov(myDataZM) -> cvm
eigen(cvm,TRUE) -> eCvm
t(eCvm$vector%*%t(myDataZM)) -> newMyData
This simple code just transforms the data to align it with the principal components obtained.
Of couse, the second way to compute them is using some of the functions that R provides in the stats package.
#
# Using the stats package
#
cbind(1:10,1:10 + 0.25*rnorm(10)) -> myData
myData - apply(myData,2,mean) -> myDataZM
prcomp(myData) -> pcaMyData
t(pcaMyData[[2]]%*%t(myDataZM)) -> newMyData
About this entry
You’re currently reading “Principal Component Analysis in R,” an entry on Xavier LlorÃ
- Published:
- Tuesday, April 24th, 2007 at 10:58 pm
- Author:
- Xavier
- Category:
- Notes
1 Comment
Jump to comment form | comments rss | trackback uri