Skip to content

Instantly share code, notes, and snippets.

@menugget
Created November 28, 2013 09:15
Show Gist options
  • Save menugget/7689201 to your computer and use it in GitHub Desktop.
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 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
}
@yasinkaymaz
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment