Solved – How to get the principal components of one matrix along the principal directions of another matrix

pcar

I have a data matrix, A, on which I have performed principal component analysis (PCA) using the prcomp function in R. This gives me the rotation (eigenvector) field and the x (rotated data) field.

Now I have another data matrix, B. I want to find the principal components of B along the principal directions of the rotation of A obtained above. How would I go about doing this?

So far, I've just calculated the two prcomp's separately and used a vector projection to project the principal components of B along the eigenvectors of A. Is this correct?

Best Answer

You get the coefficients from PCA. These coefficients are multiplied by your observation matrix to obtain the components. So, multiply rotation by the new observation matrix instead. Don't forget to center it.

Here's the code.

Run PCA and see how the score matrix is obtained from the original data and the rotation. Note, that I'm NOT centering, and you probably should.

> x=matrix(c(1,2,3,2,4,5.5),3,2)
> x
     [,1] [,2]
[1,]    1  2.0
[2,]    2  4.0
[3,]    3  5.5
> r=prcomp(x,retx=1,center=FALSE)
> r$rotation
                PC1        PC2
    [1,] -0.4666132  0.8844615
    [2,] -0.8844615 -0.4666132
    > r$x
           PC1         PC2
[1,] -2.235536 -0.04876479
[2,] -4.471072 -0.09752958
[3,] -6.264378  0.08701220
> x %*% r$rotation
           PC1         PC2
[1,] -2.235536 -0.04876479
[2,] -4.471072 -0.09752958
[3,] -6.264378  0.08701220

Now, apply the same rotation to the different data (again, see that I am NOT centering).

> y=matrix(c(1,2,3,2,4,6.5),3,2)
> y
     [,1] [,2]
[1,]    1  2.0
[2,]    2  4.0
[3,]    3  6.5
> y %*% r$rotation
           PC1         PC2
[1,] -2.235536 -0.04876479
[2,] -4.471072 -0.09752958
[3,] -7.148839 -0.37960095

Note the similarity of the new scores.

By the way, this is used a lot in forecasting with PCA. We obtain the rotation on historical data, then apply it to new data.