The code
require(graphics)
## the variances of the variables in the
## USArrests data vary by orders of magnitude, so scaling is appropriate
res<-prcomp(USArrests, scale = TRUE, retx=TRUE)
computes the principal components, in the result res$center
you find the centers, in the result res$scale
the scaling factors and in res$rotation
you find the coefficients for transforming the centered data to the pcs.
As I use the option retx=TRUE
in the above call to prcomp, res$x
contains the prinicpal components computed by prcomp().
You can yourself compute res$x as follows (and this also for 'new' observations, see at the bottom):
# center and scale the data
c.fun<-function(df, center, scale) {
return((df-center)/scale )
}
centeredData<-apply(USArrests, MARGIN=1, FUN=c.fun, res$center, res$scale )
# compute the principal components
pcs<-t(res$rotation) %*% centeredData
# compare with results of prcom (option retx=TRUE gives ^cs in x)
head(t(pcs))
head(res$x)
# check if results are the same
sum(abs(t(pcs)-res$x))
If you want to compute the components for new data, then (I use fake data) you do:
# some fake 'new data'
newdata<-USArrests[1:10,]
centeredNewData<-apply(newdata, MARGIN=1, FUN=c.fun, res$center, res$scale )
pcsnew<-t(res$rotation) %*% centeredNewData