NUMERIC_TYPES <- c("double", "integer") lsq <- function(X, y) { # TODO stopifnot("X may not be empty" = length(X) > 0) stopifnot("y may not be empty" = length(y) > 0) stopifnot("X must be numeric" = typeof(X) %in% NUMERIC_TYPES) stopifnot("y must be numeric" = typeof(y) %in% NUMERIC_TYPES) stopifnot("X must be matrix" = is.matrix(X)) stopifnot("y must be vector or matrix with one column" = is.vector(y) || (is.matrix(y) && ncol(y) == 1)) stopifnot("dimensions of X and y do not fit" = (is.vector(y) && nrow(X) == length(y)) || (is.matrix(y) && nrow(y) == nrow(X))) stopifnot("y may not contain NA" = all(!is.na(y))) stopifnot("X may not contain NA" = all(!is.na(X))) A <- t(X) %*% X stopifnot("det(t(X) %*% X) must not be zero" = det(A) != 0) solve(A, t(X) %*% y) } lsq(matrix(1:6, nrow=3), 1:3) lsq(matrix(runif(6), nrow=3), matrix(runif(3), ncol=1)) lsq(matrix(letters[1:6] , nrow=2), 1:3) lsq(matrix(1:6, nrow=3), list(1,2,3)) lsq(1:6, 1:3) lsq(matrix(1:6, nrow=3), array(1:3, dim=c(1,1,3))) lsq(matrix(1:6, nrow=3), 1:4) lsq(matrix(1:6, nrow=3), matrix(1:3, nrow=1)) lsq(matrix(1:6, nrow=3), matrix(1:6, nrow=3)) lsq(matrix(double(0), nrow=0, ncol=0), matrix(double(0), nrow=0, ncol=0)) lsq(matrix(1:6, nrow=3), c(1,NA,3)) lsq(matrix(c(1:5, NA), nrow=3), 1:3) lsq(matrix(c(1,1,2,1,1,2), nrow=3), 1:3)