rpcacross-validationggbiplot

PCA : Can I reverse the axis of the first principal component in R?


Here is a reproducible example :

set.seed(10)
pick <- sample(nrow(iris),nrow(iris)/2)
iris.training <- iris[pick,] 
iris.testing <- iris[-pick,]
pca.training <- prcomp(iris.training[-5])
pca.testing <- prcomp(iris.testing[-5])
autoplot(pca.training,loadings.label=T,loadings=T)
autoplot(pca.testing,loadings.label=T,loadings=T)

Which produces the following output : biplot_pca_training biplot_pca_testing

As one can see, pca on data.training and on data.testing produces very similar biplots but the first principal components has reversed its sign, they are mirrored. Is it possible to force a 180 degree rotation on the two components ?


Solution

  • You are not returning the rotated variables. Changed code is as below. Notice retx=TRUE

    set.seed(10)
    pick <- sample(nrow(iris),nrow(iris)/2)
    iris.training <- iris[pick,] 
    iris.testing <- iris[-pick,]
    pca.training <- prcomp(iris.training[-5], retx=TRUE)
    pca.testing <- prcomp(iris.testing[-5], retx=TRUE)
    autoplot(pca.training,loadings.label=TRUE,loadings=TRUE)
    autoplot(pca.testing,loadings.label=TRUE,loadings=TRUE)
    

    It produced the following outputs for training and testing. Training PCA plot Testing PCA plot