Created
November 28, 2013 09:15
-
-
Save menugget/7689201 to your computer and use it in GitHub Desktop.
Reconstruct a data set using PCA results from function "prcomp". A subset of PCs can be defined for truncated reconstruction.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#This function reconstructs a data set using a defined set of principal components. | |
#arguments "pca" is the pca object from prcomp, "pcs" is a vector of principal components | |
#to be used for reconstruction (default includes all pcs) | |
prcomp.recon <- function(pca, pcs=NULL){ | |
if(is.null(pcs)) pcs <- seq(pca$sdev) | |
recon <- as.matrix(pca$x[,pcs]) %*% t(as.matrix(pca$rotation[,pcs])) | |
if(pca$scale[1] != FALSE){ | |
recon <- scale(recon , center=FALSE, scale=1/pca$scale) | |
} | |
if(pca$center[1] != FALSE){ | |
recon <- scale(recon , center=-pca$center, scale=FALSE) | |
} | |
recon | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, thanks for the code. When I try this with lesser components, I always get some negative values in reconstructed matrix. I guess this is happening at the re-scaling/re-centering part using initial values. Do you have a suggestion to fix or approximate this?
Thanks