R/Projection.R

#' Finds Euclidean norm of vector
#' @param x values of components of vector
#' @return Euclidean norm of x
#' @export
euclidean_norm <- function(x) {
  sqrt(sum(x^2))
}

#' Scales the rows of a matrix
#' @param x a matrix containing rows to be scaled
#' @param ... additional arguments to pass to \code{\link[base]{scale}}
#' @return the matrix x with scaled rows
#' @export
scale_rows <- function(x, ...) {
  t(scale(t(x), ...))
}

#' Calculates the projection of an expression matrix onto a gene set matrix
#' @param expr.mat matrix containing expression of genes (rows) in samples (columns)
#' @param gs.mat matrix containing fold changes of genes (rows) for each gene set (columns)
#' @return projection scores for each gene set (row) for each sample (column)
#' @examples
#' gs.mat <- matrix(rnorm(20), nrow=10, ncol=2)
#' expr.mat <- matrix(rnorm(50), nrow=10, ncol=5)
#' projection(expr.mat, gs.mat)
#' @export
projection <- function(expr.mat, gs.mat) {
  # Input validation
  if (!is.matrix(gs.mat) || !is.matrix(expr.mat)) {
    stop("Gene set and expression matrices must be matrix type.")
  }
  if (!is.numeric(gs.mat) || !is.numeric(expr.mat)) {
    stop("Gene set and expression matrices must be numeric.")
  }
  if (nrow(gs.mat) != nrow(expr.mat)) {
    stop("Gene set and expression matrices must have same number of rows.")
  }
  # Normalize columns to unit vectors
  normaliz.factor <- apply(gs.mat, 2, euclidean_norm)
  if (any(normaliz.factor == 0)) {
    warning("At least one gene set has 0 norm.")
  }
  gs.mat2 <- sweep(gs.mat, 2, normaliz.factor, "/")
  # Compute projection of expression matrix onto gene set matrix
  t(gs.mat2) %*% expr.mat
}
agentlans/ShadowPlayer documentation built on May 15, 2019, 12:04 p.m.