R/project_pca.R

#' Project new data in existing PCA space
#'
#'inputs:
#'@param Xnew: new data matrix to project.
#'@param pc: prcomp object used for projection generated by \link[stats]{prcomp}. Must have the same number of columns as X.
#'
#'@return Xpc: a matrix that corresponds to the projection of X in the PCA space. Xpc[,1] is the first PC, Xpc[,2] the second PC, etc.
#'
#'@examples
#'
#' set.seed(1)
#' data(iris)
#'
#' #randomly select 100 data points from the iris data set
#' #to perform PCA
#' ix=rep(FALSE,nrow(iris))
#' ix[sample(nrow(iris),100)]=TRUE
#'
#' # perform PCA
#' pc=stats::prcomp(iris[ix,1:4])
#'
#' # plot the PCA
#' plot_pca(pc,col=iris$Species[ix])
#'
#' # project the remaining 50 data points (given by !ix) in the existing PCA space
#' Xpc=project_pca(iris[!ix,1:4],pc)
#'
#' #plot the new data points in the existing plot
#' points(Xpc[,1],Xpc[,2])
#'@export
project_pca = function(Xnew=NULL, pc=NULL)
{
  return(scale(Xnew, pc$center, pc$scale) %*% pc$rotation) #map new data to PCA space
}
nchlis/pca.utils documentation built on May 23, 2019, 1:06 p.m.