### Install pcaMethods via BiocManager Source: https://github.com/hredestig/pcamethods/blob/devel/README.md Install the pcaMethods package from Bioconductor using BiocManager. Requires the BiocManager package to be installed first. ```R if (!requireNamespace("BiocManager", quietly=TRUE)) install.packages("BiocManager") BiocManager::install("pcaMethods") ``` -------------------------------- ### nni example with llsImpute Source: https://github.com/hredestig/pcamethods/blob/devel/man/nni.Rd Loads the example metabolite data and applies nearest neighbour imputation using the nni wrapper with the llsImpute method, specifying k=6 and allGenes=TRUE. ```r data(metaboliteData) llsRes <- nni(metaboliteData, k=6, method="llsImpute", allGenes=TRUE) ``` -------------------------------- ### Example: robustSvd on metabolite data with outliers Source: https://github.com/hredestig/pcamethods/blob/devel/man/robustSvd.Rd Loads a complete metabolite dataset, mean-centers it, creates 5% outliers, and compares conventional SVD with robustSvd on both original and outlier-contaminated data. The example then plots the first right singular vectors to show that robustSvd is hardly affected by outliers. ```R ## Load a complete sample metabolite data set and mean center the data data(metaboliteDataComplete) mdc <- prep(metaboliteDataComplete, center=TRUE, scale="none") ## Now create 5\% of outliers. cond <- runif(length(mdc)) < 0.05; mdcOut <- mdc mdcOut[cond] <- 10 ## Now we do a conventional SVD and a robustSvd on both, the original and the ## data with outliers. resSvd <- svd(mdc) resSvdOut <- svd(mdcOut) resRobSvd <- robustSvd(mdc) resRobSvdOut <- robustSvd(mdcOut) ## Now we plot the results for the original data against those with outliers ## We can see that robustSvd is hardly affected by the outliers. plot(resSvd$v[,1], resSvdOut$v[,1]) plot(resRobSvd$v[,1], resRobSvdOut$v[,1]) ``` -------------------------------- ### Access pcaMethods documentation Source: https://github.com/hredestig/pcamethods/blob/devel/README.md Open the package vignettes and get help for a specific function. Replace with the actual function name. ```R browseVignettes("pcaMethods") ? ``` -------------------------------- ### llsImpute example with metaboliteData Source: https://github.com/hredestig/pcamethods/blob/devel/man/llsImpute.Rd Loads the sample metabolite dataset and performs LLS imputation with k=10 and allVariables=TRUE because there are very few complete variables. Then retrieves the estimated complete observations via completeObs(). ```r ## Load a sample metabolite dataset (metaboliteData) with already 5\% of ## data missing data(metaboliteData) ## Perform llsImpute using k = 10 ## Set allVariables TRUE because there are very few complete variables result <- llsImpute(metaboliteData, k = 10, correlation="pearson", allVariables=TRUE) ## Get the estimated complete observations cObs <- completeObs(result) ``` -------------------------------- ### Run svdPca and pca with method="svd" on metaboliteDataComplete Source: https://github.com/hredestig/pcamethods/blob/devel/man/svdPca.Rd Example from the svdPca documentation. Loads the metaboliteDataComplete dataset, pre-processes it with prep(), and performs PCA with svdPca() using nPcs=2. The comment recommends using pca() instead, and the example then shows the equivalent pca() call with method="svd". The \dontshow block is a test assertion that the fitted values are close to the original data. ```r data(metaboliteDataComplete) mat <- prep(t(metaboliteDataComplete)) pc <- svdPca(mat, nPcs=2) ## better use pca() pc <- pca(t(metaboliteDataComplete), method="svd", nPcs=2) \dontshow{stopifnot(sum((fitted(pc) - t(metaboliteDataComplete))^2, na.rm=TRUE) < 200)} ``` -------------------------------- ### NLPCA example with helix data Source: https://github.com/hredestig/pcamethods/blob/devel/man/nlpca.Rd Uses the helix dataset, introduces missing values, and applies nlpca with 50 steps. Plots fitted vs original missing values. Also compares with Nipals PCA. ```r ## Data set with three variables where data points constitute a helix data(helix) helixNA <- helix ## not a single complete observation helixNA <- t(apply(helix, 1, function(x) { x[sample(1:3, 1)] <- NA; x})) ## 50 steps is not enough, for good estimation use 1000 helixNlPca <- pca(helixNA, nPcs=1, method="nlpca", maxSteps=50) fittedData <- fitted(helixNlPca, helixNA) plot(fittedData[which(is.na(helixNA))], helix[which(is.na(helixNA))]) ## compared to solution by Nipals PCA which cannot extract non-linear patterns helixNipPca <- pca(helixNA, nPcs=2) fittedData <- fitted(helixNipPca) plot(fittedData[which(is.na(helixNA))], helix[which(is.na(helixNA))]) ``` -------------------------------- ### Run svdImpute via pca() on metaboliteData Source: https://github.com/hredestig/pcamethods/blob/devel/man/svdImpute.Rd Example from the svdImpute documentation. Loads the metaboliteData dataset, applies the pca() wrapper with method="svdImpute" and nPcs=3, retrieves the completed observations with completeObs(), and plots the scores with plotPcs(). ```R ## Load a sample metabolite dataset with 5\% missing values data(metaboliteData) ## Perform svdImpute using the 3 largest components result <- pca(metaboliteData, method="svdImpute", nPcs=3, center = TRUE) ## Get the estimated complete observations cObs <- completeObs(result) ## Now plot the scores plotPcs(result, type = "scores") ``` -------------------------------- ### fitted(pcaRes) Source: https://github.com/hredestig/pcamethods/blob/devel/man/fitted-methods.Rd Documentation for the fitted method for pcaRes objects, including usage, arguments, return value, and an example. ```APIDOC ## fitted(pcaRes) ### Description Extracts fitted values from a PCA model. For standard PCA methods, this is essentially scores multiplied by loadings, adjusted for pre-processing. For non-linear PCA, the original data is propagated through the network to obtain the approximated data. ### Method fitted (S3 and S4 methods) ### Signature `fitted(object, data = NULL, nPcs = nP(object), pre = TRUE, post = TRUE, ...)` ### Parameters - **object** (pcaRes) - Required - The `pcaRes` object of interest. - **data** (matrix/data.frame) - Optional - For standard PCA methods, can be left NULL to get scores x loadings. If set, scores are obtained by projecting the provided data onto the loadings. If data contains missing values, the result will be all NA. For non-linear PCA, if NULL, data is set to the completeObs and propagated through the network. - **nPcs** (numeric) - Optional - The number of principal components to consider. - **pre** (logical) - Optional - Pre-process `data` based on the pre-processing chosen for the PCA model. - **post** (logical) - Optional - Unpre-process the final data (add the center back etc.) to get the final estimate. - **...** - Not used. ### Return Value A matrix representing the fitted data. ### Example ```r pc <- pca(iris[,1:4], nPcs=4, center=TRUE, scale="uv") sum( (fitted(pc) - iris[,1:4])^2 ) ``` ``` -------------------------------- ### Run NIPALS PCA with RnipalsPca and nipalsPca Source: https://github.com/hredestig/pcamethods/blob/devel/man/RnipalsPca.Rd Example usage of RnipalsPca and nipalsPca on the metaboliteData dataset. Prepares the data with prep(), compares timing of the R and C++ implementations, and recommends using the pca() wrapper instead of calling RnipalsPca directly. ```r data(metaboliteData) mat <- prep(t(metaboliteData)) ## c++ version is faster system.time(pc <- RnipalsPca(mat, method="rnipals", nPcs=2)) system.time(pc <- nipalsPca(mat, nPcs=2)) ## better use pca() pc <- pca(t(metaboliteData), method="rnipals", nPcs=2) \dontshow{stopifnot(sum((fitted(pc) - t(metaboliteData))^2, na.rm=TRUE) < 200)} ``` -------------------------------- ### NIPALS PCA example using nipalsPca and pca() wrapper Source: https://github.com/hredestig/pcamethods/blob/devel/man/nipalsPca.Rd Demonstrates basic usage of nipalsPca on the metaboliteData dataset after preprocessing with prep(). The comment recommends using the pca() wrapper instead, and the code shows an equivalent pca() call with method="nipals". The \dontshow block runs an internal check that fitted values are close to the original data. ```r data(metaboliteData) mat <- prep(t(metaboliteData)) pc <- nipalsPca(mat, nPcs=2) ## better use pca() pc <- pca(t(metaboliteData), method="nipals", nPcs=2) \dontshow{stopifnot(sum((fitted(pc) - t(metaboliteData))^2, na.rm=TRUE) < 200)} ``` -------------------------------- ### Basic pca() usage with iris dataset Source: https://github.com/hredestig/pcamethods/blob/devel/man/pca.Rd Basic usage of pca() on the iris dataset with svd and nipals methods, followed by summary, plot, and slplot calls. The example notes that scaling is usually appropriate. ```R data(iris) ## Usually some kind of scaling is appropriate pcIr <- pca(iris, method="svd", nPcs=2) pcIr <- pca(iris, method="nipals", nPcs=3, cv="q2") ## Get a short summary on the calculated model summary(pcIr) plot(pcIr) ## Scores and loadings plot slplot(pcIr, sl=as.character(iris[,5])) ``` -------------------------------- ### pca() on ExpressionSet with ggplot2 plotting Source: https://github.com/hredestig/pcamethods/blob/devel/man/pca.Rd Demonstrates pca() on an ExpressionSet object and plotting the scores with ggplot2. The example merges scores with phenotype data and uses the R2 slot for axis labels. ```R ## use an expressionset and ggplot data(sample.ExpressionSet) pc <- pca(sample.ExpressionSet) df <- merge(scores(pc), pData(sample.ExpressionSet), by=0) library(ggplot2) ggplot(df, aes(PC1, PC2, shape=sex, color=type)) + geom_point() + xlab(paste("PC1", pc@R2[1] * 100, "\% of the variance")) + ylab(paste("PC2", pc@R2[2] * 100, "\% of the variance")) ``` -------------------------------- ### robustPca example: compare PCA and robustPca on data with outliers Source: https://github.com/hredestig/pcamethods/blob/devel/man/robustPca.Rd Demonstrates robustPca on a complete metabolite data set with artificially introduced outliers. It compares conventional PCA (method="svd") and robustPca on the outlier-contaminated data, using center=FALSE to avoid the large artificial outliers affecting the means. The final plots show that robustPca loadings are hardly affected by the outliers. ```R data(metaboliteDataComplete) mdc <- scale(metaboliteDataComplete, center=TRUE, scale=FALSE) ## Now create 5\% of outliers. cond <- runif(length(mdc)) < 0.05; mdcOut <- mdc mdcOut[cond] <- 10 ## Now we do a conventional PCA and robustPca on the original and the data ## with outliers. ## We use center=FALSE here because the large artificial outliers would ## affect the means and not allow to objectively compare the results. resSvd <- pca(mdc, method="svd", nPcs=10, center=FALSE) resSvdOut <- pca(mdcOut, method="svd", nPcs=10, center=FALSE) resRobPca <- pca(mdcOut, method="robustPca", nPcs=10, center=FALSE) ## Now we plot the results for the original data against those with outliers ## We can see that robustPca is hardly effected by the outliers. plot(loadings(resSvd)[,1], loadings(resSvdOut)[,1]) plot(loadings(resSvd)[,1], loadings(resRobPca)[,1]) ``` -------------------------------- ### pca Source: https://github.com/hredestig/pcamethods/blob/devel/man/bpca.Rd Performs Principal Component Analysis using the specified method (e.g., 'bpca') on a data matrix. The example demonstrates loading a sample dataset, performing Bayesian PCA with 2 components, and extracting results. ```APIDOC ## pca ### Description Performs Principal Component Analysis (PCA) using the specified method (e.g., 'bpca' for Bayesian PCA) on a data matrix. The example demonstrates loading a sample metabolite dataset, performing Bayesian PCA with 2 components, and extracting loadings, scores, and complete observations. ### Usage ```r pca(t(metaboliteData), method="bpca", nPcs=2) ``` ### Arguments - **data** (matrix) - Required - A numeric matrix where rows are samples and columns are variables. In the example, the metabolite dataset is transposed. - **method** (character) - Required - The PCA method to use. Supported methods include "bpca", "ppca", "svdImpute", "prcomp", "nipalsPca". - **nPcs** (numeric) - Required - The number of principal components to compute. ### Details The function performs PCA using the specified method. For Bayesian PCA (method="bpca"), it estimates missing values and computes principal components. ### Value Returns an object of class 'pcaRes' containing the PCA results, including loadings, scores, and complete observations. ### Examples ```r # Load a sample metabolite dataset with 5% missing values (metaboliteData) data(metaboliteData) # Perform Bayesian PCA with 2 components pc <- pca(t(metaboliteData), method="bpca", nPcs=2) # Get the estimated principal axes (loadings) loadings <- loadings(pc) # Get the estimated scores scores <- scores(pc) # Get the estimated complete observations cObs <- completeObs(pc) # Now make a scores and loadings plot slplot(pc) ``` ### See Also - ppca - svdImpute - prcomp - nipalsPca - pcaRes - kEstimate ### Author Wolfram Stacklies ### References Shigeyuki Oba, Masa-aki Sato, Ichiro Takemasa, Morito Monden, Ken-ichi Matsubara and Shin Ishii. A Bayesian missing value estimation method for gene expression profile data. *Bioinformatics*, 19(16):2088-2096, Nov 2003. ``` -------------------------------- ### Create a biplot of PCA results with iris data Source: https://github.com/hredestig/pcamethods/blob/devel/man/biplot-methods.Rd Loads the iris dataset, performs PCA on the first four columns, and creates a biplot. The example shows the basic usage of the biplot method on a pcaRes object. ```R data(iris) pcIr <- pca(iris[,1:4]) biplot(pcIr) ``` -------------------------------- ### slplot example with iris dataset Source: https://github.com/hredestig/pcamethods/blob/devel/man/slplot-pcaRes-method.Rd Creates a pcaRes object from the iris dataset and generates side-by-side scores and loadings plots. The first call uses default settings with no score labels and a custom point character. The second call adds custom loadings label size and colors scores by iris species. ```r data(iris) pcIr <- pca(iris[,1:4], scale="uv") slplot(pcIr, sl=NULL, spch=5) slplot(pcIr, sl=NULL, lcex=1.3, scol=as.integer(iris[,5])) ``` -------------------------------- ### Predict PCA scores on new data Source: https://github.com/hredestig/pcamethods/blob/devel/man/predict-methods.Rd Example from the predict-methods documentation. It loads the iris dataset, splits it into a training and hidden test set, builds PCA models on the training set and the full data, predicts scores for the hidden observations, and compares the first predicted score with the corresponding score from the full model using correlation. ```r data(iris) hidden <- sample(nrow(iris), 50) pcIr <- pca(iris[-hidden,1:4]) pcFull <- pca(iris[,1:4]) irisHat <- predict(pcIr, iris[hidden,1:4]) cor(irisHat$scores[,1], scores(pcFull)[hidden,1]) ``` -------------------------------- ### Extract leverages from PCA model on iris data Source: https://github.com/hredestig/pcamethods/blob/devel/man/leverage-pcaRes-method.Rd Fits a PCA model to the first four columns of the iris dataset and plots the leverages against the Species variable. The example notes that versicolor has the lowest leverage. ```r data(iris) pcIr <- pca(iris[,1:4]) ## versicolor has the lowest leverage with(iris, plot(leverage(pcIr)~Species)) ``` -------------------------------- ### Use wasna to compare imputed and complete data Source: https://github.com/hredestig/pcamethods/blob/devel/man/wasna-pcaRes-method.Rd Loads example metabolite data, performs PCA with two principal components, and plots the imputed values (from completeObs) against the complete data for the missing positions indicated by wasna. This is useful for visually assessing imputation performance. ```R data(metaboliteData) data(metaboliteDataComplete) result <- pca(metaboliteData, nPcs=2) plot(completeObs(result)[wasna(result)], metaboliteDataComplete[wasna(result)]) ``` -------------------------------- ### cvstat(object, ...) Source: https://github.com/hredestig/pcamethods/blob/devel/man/cvstat-pcaRes-method.Rd Get cross-validation statistics (e.g. Q^2) from a pcaRes object. ```APIDOC ## cvstat(object, ...) ### Description Get cross-validation statistics (e.g. Q^2) from a pcaRes object. ### Usage cvstat(object, ...) ### Arguments - **object** (pcaRes) - Required - A pcaRes object. - **...** - Optional - Not used. ### Value vector CV statistics ``` -------------------------------- ### scores.pcaRes(object, ...) Source: https://github.com/hredestig/pcamethods/blob/devel/man/scores.pcaRes.Rd Get scores from a pcaRes object. This method returns the scores as a matrix. ```APIDOC ## scores.pcaRes(object, ...) ### Description Get scores from a pcaRes object. ### Usage \method{scores}{pcaRes}(object, ...) ### Arguments - **object** (pcaRes) - Required - a pcaRes object - **...** - Optional - not used ### Value The scores as a matrix ### Author Henning Redestig ``` -------------------------------- ### prep Source: https://github.com/hredestig/pcamethods/blob/devel/man/prep.Rd Documentation for the prep function, which scales and centers a matrix for PCA. ```APIDOC ## prep ### Description Pre-process a matrix for PCA by scaling and centering. Supports multiple scaling methods and can also reverse the pre-processing. ### Usage prep(object, scale = c("none", "pareto", "vector", "uv"), center = TRUE, eps = 1e-12, simple = TRUE, reverse = FALSE, ...) ### Arguments - **object** (matrix or ExpressionSet) - Required - Numerical matrix with samples in rows and variables as columns. Also accepts ExpressionSet, in which case the transposed expression matrix is used. - **scale** (character or numeric vector) - Optional - Scaling method: "UV" (unit variance), "vector" (vector normalisation), "pareto" (sqrt UV), or "none". Can also be a vector of scales to use. NULL is interpreted as "none". - **center** (logical or numeric vector) - Optional - Logical indicating if matrix should be mean centred, or a vector of averages to subtract. NULL is interpreted as FALSE. - **eps** (numeric) - Optional - Minimum variance; variables with lower variance are not scaled and a warning is issued. - **simple** (logical) - Optional - If TRUE, only the pre-processed data is returned; if FALSE, a list with pre-processing statistics is returned. - **reverse** (logical) - Optional - If TRUE, the matrix is 'post-processed' by multiplying each column by its scale and adding the center. In this case, center and scale should be vectors with the statistics. - **...** - Optional - Only used for passing through arguments. ### Value A pre-processed matrix, or a list with: - **center** (numeric vector) - Estimated centers - **scale** (numeric vector) - Estimated scales - **data** (matrix) - The pre (or post) processed data ### Details Does basically the same as `scale` but adds alternative scaling options and functionality for treating pre-processing as part of a model. ### Examples ```r object <- matrix(rnorm(50), nrow=10) res <- prep(object, scale="uv", center=TRUE, simple=FALSE) obj <- prep(object, scale=res$scale, center=res$center) ## same as original sum((object - prep(obj, scale=res$scale, center=res$center, rev=TRUE))^2) ``` ``` -------------------------------- ### Calculate R2 for PCA model Source: https://github.com/hredestig/pcamethods/blob/devel/man/R2VX-pcaRes-method.Rd Calculates R2 goodness of fit for a PCA model. The example uses the built-in iris dataset. ```R R2VX(pca(iris)) ``` -------------------------------- ### weightsAccount(w) Source: https://github.com/hredestig/pcamethods/blob/devel/man/weightsAccount.Rd Constructor function for a weightsAccount object used in nlpcaNet. It initializes the account with a weight matrix and provides set and current functions for weight management. ```APIDOC ## weightsAccount(w) ### Description Creates an object that holds the weights for an nlpcaNet. The object stores and updates weights using an environment, and provides `set` and `current` functions to modify and retrieve the weights. ### Usage ```r weightsAccount(w) ``` ### Arguments - **w** (`matrix`) - Required - New weights to initialize the account. ### Value A weightsAccount object with `set` and `current` functions. ``` -------------------------------- ### nObs(object, ...) Source: https://github.com/hredestig/pcamethods/blob/devel/man/nObs-pcaRes-method.Rd Get the number of observations used to build the PCA model. This method takes a pcaRes object and returns the number of observations. ```APIDOC ## nObs(object, ...) ### Description Get the number of observations used to build the PCA model. ### Usage nObs(object, ...) ### Arguments - **object** (pcaRes) - Required - A pcaRes object. - **...** - Optional - Not used. ### Value Number of observations (numeric). ### Author Henning Redestig ``` -------------------------------- ### sDev(object, ...) Source: https://github.com/hredestig/pcamethods/blob/devel/man/sDev-pcaRes-method.Rd Get the standard deviations of the scores (indicates their relevance). The method takes a pcaRes object and returns the standard deviations of the scores. ```APIDOC ## sDev(object, ...) ### Description Get the standard deviations of the scores (indicates their relevance). ### Usage sDev(object, ...) ### Arguments - **object** (pcaRes) - Required - pcaRes object - **...** - Not used ### Value Standard devations of the scores ``` -------------------------------- ### forkNlpcaNet Source: https://github.com/hredestig/pcamethods/blob/devel/man/forkNlpcaNet.Rd Function to create a complete copy of an nlpca net object. ```APIDOC ## forkNlpcaNet(nlnet) ### Description Complete copy of nlpca net object. ### Usage ```r forkNlpcaNet(nlnet) ``` ### Arguments - **nlnet** - a nlnet ### Value A copy of the input nlnet ``` -------------------------------- ### Run kEstimate with ppca and plot NRMSEP results Source: https://github.com/hredestig/pcamethods/blob/devel/man/kEstimate.Rd Loads the metaboliteData dataset and runs kEstimate with ppca for components 2:4, then plots the average NRMSEP and the variable-wise estimation error for the best number of PCs. ```r ## Load a sample metabolite dataset with 5\% missing values (metaboliteData) data(metaboliteData) # Do cross validation with ppca for component 2:4 esti <- kEstimate(metaboliteData, method = "ppca", evalPcs = 2:4, nruncv=1, em="nrmsep") # Plot the average NRMSEP barplot(drop(esti$eError), xlab = "Components",ylab = "NRMSEP (1 iterations)") # The best result was obtained for this number of PCs: print(esti$bestNPcs) # Now have a look at the variable wise estimation error barplot(drop(esti$variableWiseError[, which(esti$evalPcs == esti$bestNPcs)]), xlab = "Incomplete variable Index", ylab = "NRMSEP") ``` -------------------------------- ### kEstimateFast(Matrix, method = "ppca", evalPcs = 1:3, em = "nrmsep", allVariables = FALSE, verbose = interactive(), ...) Source: https://github.com/hredestig/pcamethods/blob/devel/man/kEstimateFast.Rd Documentation for the kEstimateFast function, which estimates the optimal number of components for missing value estimation using PCA or LLSimpute. ```APIDOC ## kEstimateFast(Matrix, method = "ppca", evalPcs = 1:3, em = "nrmsep", allVariables = FALSE, verbose = interactive(), ...) ### Description Estimates the best number of components for missing value estimation using PCA or LLSimpute. The estimation quality is defined as Matrix[!missing] - Estimate[!missing], providing a rough estimate without cross-validation. ### Usage ```r kEstimateFast(Matrix, method = "ppca", evalPcs = 1:3, em = "nrmsep", allVariables = FALSE, verbose = interactive(), ...) ``` ### Arguments - **Matrix** (`matrix`) - Required - Numeric matrix containing observations in rows and variables in columns. - **method** (`character`) - Optional - A valid pca method (see `pca`). Default is `"ppca"`. - **evalPcs** (`numeric`) - Optional - The principal components to use for cross validation or cluster sizes if used with llsImpute. Should be an array containing integer values, e.g., `evalPcs = 1:10` or `evalPcs = c(2,5,8)`. The NRMSEP is calculated for each component. Default is `1:3`. - **em** (`character`) - Optional - The error measure. Can be `"nrmsep"` or `"q2"`. Default is `"nrmsep"`. - **allVariables** (`boolean`) - Optional - If TRUE, the NRMSEP is calculated for all variables; if FALSE, only the incomplete ones are included. Default is FALSE. - **verbose** (`boolean`) - Optional - If TRUE, the NRMSEP and the variance are printed to the console each iteration. Default is `interactive()`. - **...** - Further arguments to `pca`. ### Value Returns a list with the elements: - **minNPcs** - Number of PCs for which the minimal average NRMSEP was obtained. - **eError** - An array of size length(evalPcs) containing the estimation error for each number of components. - **evalPcs** - The evaluated numbers of components or cluster sizes (same as the evalPcs input parameter). ### Details This is a simple estimator for the optimal number of components when applying PCA or LLSimpute for missing value estimation. No cross validation is performed; instead, the estimation quality is defined as Matrix[!missing] - Estimate[!missing]. This gives a relatively rough estimate, but the number of iterations equals the length of the parameter evalPcs. Does not work with LLSimpute. As error measure, the NRMSEP (see Feten et al., 2005) or the Q2 distance is used. The NRMSEP basically normalises the RMSD between original data and estimate by the variable-wise variance. If the number of samples is small, the gene-wise variance may become an unstable criterion and the Q2 distance should be used instead. Also if variance normalisation was applied previously. ### Examples ```r data(metaboliteData) # Estimate best number of PCs with ppca for component 2:4 esti <- kEstimateFast(t(metaboliteData), method = "ppca", evalPcs = 2:4, em="nrmsep") barplot(drop(esti$eError), xlab = "Components", ylab = "NRMSEP (1 iterations)") # The best k value is: print(esti$minNPcs) ``` ### See Also `kEstimate` ### Author Wolfram Stacklies ``` -------------------------------- ### Estimate optimal number of PCs with kEstimateFast Source: https://github.com/hredestig/pcamethods/blob/devel/man/kEstimateFast.Rd Loads the metaboliteData dataset, estimates the best number of principal components using the ppca method for components 2 through 4, plots the NRMSEP error for each component, and prints the optimal number of components. ```R data(metaboliteData) # Estimate best number of PCs with ppca for component 2:4 esti <- kEstimateFast(t(metaboliteData), method = "ppca", evalPcs = 2:4, em="nrmsep") barplot(drop(esti$eError), xlab = "Components",ylab = "NRMSEP (1 iterations)") # The best k value is: print(esti$minNPcs) ``` -------------------------------- ### repmat(mat, M, N) Source: https://github.com/hredestig/pcamethods/blob/devel/man/repmat.Rd Creates a large matrix B consisting of an M-by-N tiling of copies of the input matrix mat. ```APIDOC ## repmat(mat, M, N) ### Description Creates a large matrix B consisting of an M-by-N tiling of copies of the input matrix mat. ### Usage ```r repmat(mat, M, N) ``` ### Arguments - **mat** (numeric matrix) - Required - Input matrix to be replicated. - **M** (numeric) - Required - Number of copies in vertical direction. - **N** (numeric) - Required - Number of copies in horizontal direction. ### Value Matrix consisting of M-by-N tiling copies of the input matrix. ### Author Wolfram Stacklies ``` -------------------------------- ### listPcaMethods(which = c("all", "linear", "nonlinear")) Source: https://github.com/hredestig/pcamethods/blob/devel/man/listPcaMethods.Rd Returns a character vector of currently valid PCA methods. The 'which' argument can be used to filter methods by type: 'all' for all methods, 'linear' for methods based on the classical linear model, or 'nonlinear' for nonlinear methods. ```APIDOC ## listPcaMethods ### Description Vector with current valid PCA methods ### Usage listPcaMethods(which = c("all", "linear", "nonlinear")) ### Arguments - **which** (character) - Optional - The type of methods to get. E.g. only get the PCA methods based on the classical model where the fitted data is a direct multiplication of scores and loadings. ### Value A character vector with the current methods for doing PCA ### Details This function returns a character vector of the currently valid PCA methods. The `which` parameter allows filtering by method type: `"all"` for all methods, `"linear"` for linear methods, and `"nonlinear"` for nonlinear methods. ### Author Henning Redestig ``` -------------------------------- ### R2VX,pcaRes-method Source: https://github.com/hredestig/pcamethods/blob/devel/man/R2VX-pcaRes-method.Rd Documentation for the R2VX method applied to pcaRes objects, which calculates R2 goodness of fit. ```APIDOC ## R2VX(pcaRes) ### Description Flexible calculation of R2 goodness of fit for a PCA model. ### Method R2VX ### Signature `R2VX(object, direction = c("variables", "observations", "complete"), data = completeObs(object), pcs = nP(object))` ### Parameters - **object** (pcaRes) - Required - A PCA model object. - **direction** (character) - Optional - Choose between calculating R2 per variable, per observation, or for the entire data with 'variables', 'observations', or 'complete'. Default is c("variables", "observations", "complete"). - **data** (matrix/data.frame) - Optional - The data used to fit the model. Default is completeObs(object). - **pcs** (numeric) - Optional - The number of PCs to use to calculate R2. Default is nP(object). ### Return Value A vector with R2 values. ### Example ```r R2VX(pca(iris)) ``` ``` -------------------------------- ### summary(pcaRes) Source: https://github.com/hredestig/pcamethods/blob/devel/man/summary.Rd Prints a brief description of a PCA model object. ```APIDOC ## summary(pcaRes) ### Description Print a brief description of the PCA model. ### Method summary ### Signature summary(object, ...) ### Parameters - **object** (pcaRes) - Required - A pcaRes object. - **...** - Optional - Not used. ### Return Value Nothing, used for side-effect. ``` -------------------------------- ### pca Source: https://github.com/hredestig/pcamethods/blob/devel/man/pca.Rd Documentation for the pca function, a wrapper for various PCA methods. ```APIDOC ## pca(object, method, nPcs = 2, scale = c("none", "pareto", "vector", "uv"), center = TRUE, completeObs = TRUE, subset = NULL, cv = c("none", "q2"), ...) ### Description Perform principal component analysis on a numeric matrix for visualisation, information extraction and missing value imputation. ### Usage pca(object, method, nPcs = 2, scale = c("none", "pareto", "vector", "uv"), center = TRUE, completeObs = TRUE, subset = NULL, cv = c("none", "q2"), ...) ### Parameters - **object** (matrix, ExpressionSet, or data.frame) - Required - Numerical matrix with samples in rows and variables as columns. Also accepts ExpressionSet (transposed expression matrix used) or a data frame (all numeric variables used). - **method** (character) - Required - One of the methods reported by listPcaMethods(). Can be left missing; svd PCA is chosen for data without missing values and nipalsPca for data with missing values. - **nPcs** (numeric) - Optional - Number of principal components to calculate. Default: 2. - **scale** (character) - Optional - Scaling method, see prep. Default: "none". - **center** (logical) - Optional - Centering, see prep. Default: TRUE. - **completeObs** (logical) - Optional - Sets the completeObs slot on the resulting pcaRes object containing the original data with all NAs replaced with estimates. Default: TRUE. - **subset** (character or numeric) - Optional - A subset of variables to use for calculating the model. Can be column names or indices. - **cv** (character) - Optional - Type of cross-validation to be performed. Default: "none". - **...** - Optional - Arguments to prep, the chosen pca method and Q2. ### Return Value A pcaRes object. ### Details This method is a wrapper function for the following set of pca methods: - **svd**: Uses classical prcomp. See svdPca. - **nipals**: An iterative method capable of handling small amounts of missing values. See nipalsPca. - **rnipals**: Same as nipals but implemented in R. - **bpca**: An iterative method using a Bayesian model to handle missing values. See bpca. - **ppca**: An iterative method using a probabilistic model to handle missing values. See ppca. - **svdImpute**: Uses expectation maximation to perform SVD PCA on incomplete data. See svdImpute. Scaling and centering is part of the PCA model and handled by prep. ### Examples ```r data(iris) ## Usually some kind of scaling is appropriate pcIr <- pca(iris, method="svd", nPcs=2) pcIr <- pca(iris, method="nipals", nPcs=3, cv="q2") ## Get a short summary on the calculated model summary(pcIr) plot(pcIr) ## Scores and loadings plot slplot(pcIr, sl=as.character(iris[,5])) ## use an expressionset and ggplot data(sample.ExpressionSet) pc <- pca(sample.ExpressionSet) df <- merge(scores(pc), pData(sample.ExpressionSet), by=0) library(ggplot2) ggplot(df, aes(PC1, PC2, shape=sex, color=type)) + geom_point() + xlab(paste("PC1", pc@R2[1] * 100, "\% of the variance")) + ylab(paste("PC2", pc@R2[2] * 100, "\% of the variance")) ``` ### References - Wold, H. (1966) Estimation of principal components and related models by iterative least squares. In Multivariate Analysis (Ed., P.R. Krishnaiah), Academic Press, NY, 391-420. - Shigeyuki Oba, Masa-aki Sato, Ichiro Takemasa, Morito Monden, Ken-ichi Matsubara and Shin Ishii. A Bayesian missing value estimation method for gene expression profile data. Bioinformatics, 19(16):2088-2096, Nov 2003. - Troyanskaya O. and Cantor M. and Sherlock G. and Brown P. and Hastie T. and Tibshirani R. and Botstein D. and Altman RB. - Missing value estimation methods for DNA microarrays. Bioinformatics. 2001 Jun;17(6):520-5. ### See Also prcomp, princomp, nipalsPca, svdPca ``` -------------------------------- ### llsImpute(Matrix, k = 10, center = FALSE, completeObs = TRUE, correlation = "pearson", allVariables = FALSE, maxSteps = 100, xval = NULL, verbose = FALSE, ...) Source: https://github.com/hredestig/pcamethods/blob/devel/man/llsImpute.Rd Performs local least squares imputation on a data matrix with missing values. Selects k similar variables by correlation and imputes missing values via linear regression. Returns an nniRes object with the imputed data. ```APIDOC ## llsImpute(Matrix, k = 10, center = FALSE, completeObs = TRUE, correlation = "pearson", allVariables = FALSE, maxSteps = 100, xval = NULL, verbose = FALSE, ...) ### Description Missing value estimation using local least squares (LLS). First, k variables (for microarray data usually the genes) are selected by pearson, spearman or kendall correlation coefficients. Then missing values are imputed by a linear combination of the k selected variables. The optimal combination is found by LLS regression. The method was first described by Kim et al, Bioinformatics, 21(2), 2005. ### Usage llsImpute(Matrix, k = 10, center = FALSE, completeObs = TRUE, correlation = "pearson", allVariables = FALSE, maxSteps = 100, xval = NULL, verbose = FALSE, ...) ### Parameters #### Arguments - **Matrix** (matrix) - Required - Data containing the variables (genes) in columns and observations (samples) in rows. The data may contain missing values, denoted as NA. - **k** (numeric) - Optional - Cluster size, this is the number of similar genes used for regression. Default: 10. - **center** (boolean) - Optional - Mean center the data if TRUE. Default: FALSE. - **completeObs** (boolean) - Optional - Return the estimated complete observations if TRUE. This is the input data with NA values replaced by the estimated values. Default: TRUE. - **correlation** (character) - Optional - How to calculate the distance between genes. One out of pearson | kendall | spearman. Default: "pearson". - **allVariables** (boolean) - Optional - Use only complete genes to do the regression if TRUE, all genes if FALSE. Default: FALSE. - **maxSteps** (numeric) - Optional - Maximum number of iteration steps if allVariables = TRUE. Default: 100. - **xval** (numeric) - Optional - Use LLSimpute for cross validation. xval is the index of the gene to estimate, all other incomplete genes will be ignored if this parameter is set. We do not consider them in the cross-validation. - **verbose** (boolean) - Optional - Print step number and relative change if TRUE and allVariables = TRUE. Default: FALSE. - **...** - Optional - Reserved for parameters used in future version of the algorithm. ### Return Value Returns an object of class nniRes (standard nni result object of this package). See nniRes for details. ### Details Missing values are denoted as NA. It is not recommended to use this function directly but rather to use the nni() wrapper function. The method provides two ways for missing value estimation, selected by the allVariables option. The first one is to use only complete variables for the regression. This is preferable when the number of incomplete variables is relatively small. The second way is to consider all variables as candidates for the regression. Hereby missing values are initially replaced by the column-wise mean. The method then iterates, using the current estimate as input for the regression until the change between new and old estimate falls below a threshold (0.001). ### Note Each step the generalized inverse of a miss x k matrix is calculated. Where miss is the number of missing values in variable j and k the number of neighbours. This may be slow for large values of k and / or many missing values. ### Examples ```r ## Load a sample metabolite dataset (metaboliteData) with already 5% of data missing data(metaboliteData) ## Perform llsImpute using k = 10 ## Set allVariables TRUE because there are very few complete variables result <- llsImpute(metaboliteData, k = 10, correlation="pearson", allVariables=TRUE) ## Get the estimated complete observations cObs <- completeObs(result) ``` ### References Kim, H. and Golub, G.H. and Park, H. - Missing value estimation for DNA microarray gene expression data: local least squares imputation. Bioinformatics, 2005; 21(2):187-198. Troyanskaya O. and Cantor M. and Sherlock G. and Brown P. and Hastie T. and Tibshirani R. and Botstein D. and Altman RB. - Missing value estimation methods for DNA microarrays. Bioinformatics. 2001 Jun;17(6):520-525. ### See Also pca, nniRes, nni ### Author Wolfram Stacklies ### Keywords multivariate ``` -------------------------------- ### show(pcaRes) Source: https://github.com/hredestig/pcamethods/blob/devel/man/show-methods.Rd S4 method for showing pcaRes objects. Displays basic information about the object. ```APIDOC ## show(pcaRes) ### Description Print basic information about pcaRes object ### Usage \S4method{show}{pcaRes}(object) ### Arguments - **object** (pcaRes) - Required - the object to print information about ### Value nothing, used for its side effect ### Author Henning Redestig ``` -------------------------------- ### svdPca(Matrix, nPcs = 2, varLimit = 1, verbose = interactive(), ...) Source: https://github.com/hredestig/pcamethods/blob/devel/man/svdPca.Rd Documentation for the svdPca function, a wrapper for prcomp that returns a pcaRes object. ```APIDOC ## svdPca(Matrix, nPcs = 2, varLimit = 1, verbose = interactive(), ...) ### Description A wrapper function for `prcomp` to deliver the result as a `pcaRes` method. Supplied for compatibility with the rest of the pcaMethods package. It is not recommended to use this function directly but rather to use the `pca()` wrapper function. ### Usage ```r svdPca(Matrix, nPcs = 2, varLimit = 1, verbose = interactive(), ...) ``` ### Arguments - **Matrix** (matrix) - Required - Pre-processed (centered and possibly scaled) numerical matrix samples in rows and variables as columns. No missing values allowed. - **nPcs** (numeric) - Optional - Number of components that should be extracted. Default is 2. - **varLimit** (numeric) - Optional - Optionally the ratio of variance that should be explained. `nPcs` is ignored if varLimit < 1. Default is 1. - **verbose** (logical) - Optional - Verbose complaints to matrix structure. Default is `interactive()`. - **...** - Optional - Only used for passing through arguments. ### Value A `pcaRes` object. ### Examples ```r data(metaboliteDataComplete) mat <- prep(t(metaboliteDataComplete)) pc <- svdPca(mat, nPcs=2) ## better use pca() pc <- pca(t(metaboliteDataComplete), method="svd", nPcs=2) ``` ``` -------------------------------- ### print(pcaRes) Source: https://github.com/hredestig/pcamethods/blob/devel/man/show-methods.Rd S4 method for printing pcaRes objects. Displays basic information about the object. ```APIDOC ## print(pcaRes) ### Description Print basic information about pcaRes object ### Usage \S4method{print}{pcaRes}(x, ...) ### Arguments - **x** (pcaRes) - Required - a pcaRes object - **...** - Optional - not used ### Value nothing, used for its side effect ### Author Henning Redestig ``` -------------------------------- ### Create CV segments for a number of items Source: https://github.com/hredestig/pcamethods/blob/devel/man/cvseg.Rd Generates 10 cross-validation segments for 20 items without class information. ```R cvseg(20, 10) ```