R/classSVD.R

classSVD <-
function(x){
	if(!is.matrix(x)) {
		stop("The function classSVD requires input of type 'matrix'.")
	}
	n <- nrow(x)
	p <- ncol(x)
	if(n == 1) {
		stop("The sample size is 1. No singular value decomposition can be performed.")
	}
	if(p < 5) {
		tolerance <- 1E-12
	}
	else {
		if(p <= 8) {
			tolerance <- 1E-14
		}
		else {
			tolerance <- 1E-16
		}
	}
	centerofX <- apply(x, 2, mean)
	Xcentered <- scale(x, center=TRUE, scale=FALSE)
	XcenteredSVD <- svd(Xcentered/sqrt(n-1))
	rank <- sum(XcenteredSVD$d > tolerance)
	eigenvalues <- (XcenteredSVD$d[1:rank])^2
	loadings <- XcenteredSVD$v[,1:rank]
	scores <- Xcentered %*% loadings
	return(list(loadings=as.matrix(loadings), scores=as.matrix(scores), eigenvalues=as.vector(eigenvalues), rank=rank,
					Xcentered=as.matrix(Xcentered), centerofX=as.vector(centerofX)))
}
musto101/wilcox_R documentation built on May 23, 2019, 10:52 a.m.