# A simple function to perform PCA
myPCA <- function(Y) {
Y.mat <- as.matrix(Y)
object.names <- rownames(Y)
var.names <- colnames(Y)
# Centre the data (needed to compute matrix F)
Y.cent <- scale(Y.mat, center = TRUE, scale = FALSE)
# Covariance matrix S
Y.cov <- cov(Y.cent)
# Eigenvectors and eigenvalues of S (Legendre and Legendre 2012,
# eq. 9.1 and 9.2)
Y.eig <- eigen(Y.cov)
# Copy the eigenvectors to matrix U (used to represent variables
# in scaling 1 biplots)
U <- Y.eig$vectors
rownames(U) <- var.names
# Compute matrix F (used to represent objects in scaling 1 plots)
F <- Y.cent %*% U
# eq. 9.4
rownames(F) <- object.names
The Code It Yourself corner # 2
Legendre and Legendre (2012) provide the algebra necessary to program the
ordination methods described above directly “from scratch”, i.e., using the matrix
algebra functions implemented in R. While it is not the purpose of this book to do
this for all methods, we provide an example that could stimulate the interest of
users. After all, numerical ecology is a living science, and anybody could one day
stumble upon a situation for which no ready-made function exists. The researcher
may then be interested in developing his or her own method and write the
functions to implement it.
The example below is based on the algebraic development presented in
Legendre and Legendre (2012), Sect. 9.1. It is presented in the form of a function,
the kind that any user could write for her or his own use. The steps are the
following for a PCA of a covariance matrix. To obtain a PCA of a correlation
matrix, one has to standardize the data before using this function, or implement
the standardization as an option in the function itself.
1 - Compute the covariance matrix S of the original or centred data matrix.
2 - Compute the eigenvectors and eigenvalues of S (eqs. 9.1 and 9.2).
3 - Extract matrix U of the eigenvectors and compute matrix F of the principal
components (eq. 9.4) for the scaling 1 biplot. This step involves the centred data.
4 - Compute matrices U2 and G for the scaling 2 biplot.
5 - Output of the results
5.7 Hand-Written PCA Ordination Function
199
Précédent

- 212/444

Suivant