% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/utils.R
\name{utilsAggregateRows}
\alias{utilsAggregateRows}
\alias{utilsAggregateRows,matrix-method}
\alias{utilsAggregateRows,dgCMatrix-method}
\title{Utility: Aggregate rows}
\usage{
utilsAggregateRows(x, group, drop = TRUE, sparse = FALSE)

\S4method{utilsAggregateRows}{matrix}(x, group, drop = TRUE, sparse = FALSE)

\S4method{utilsAggregateRows}{dgCMatrix}(x, group, drop = TRUE, sparse = FALSE)
}
\arguments{
\item{x}{matrix or dgCMatrix: Matrix to be aggregated.}

\item{group}{factor: Grouping, can cannot NAs which will be discarded.}

\item{drop}{logical: Whether to drop unused levels (TRUE) or keep assign them
0 (FALSE).}

\item{sparse}{logical: Whether output should be coerced to a dense matrix.}
}
\value{
matrix (or dgCMatrix if sparse=TRUE)
}
\description{
Used by quantifyClusters and quantifyGenes. Wrapper around rowsum with a few
improvements: 1) Handles dgCMatrix 2) Suppresses warnings from and discards
NAs in grouping 3) Checks if output can be coerced to integer (useful when
aggregating a dgCMatrix), 4) For the dgCMatrix case, has the option to keep
unused levels and output a sparse matrix.
}
\examples{
library(Matrix)
data("exampleCTSSs")
data("exampleUnidirectional")

# Sparse and dense examples
sparse_matrix <- assay(exampleCTSSs)
dense_matrix <- as(sparse_matrix, "matrix")

# Groupings
grp <- findOverlaps(query = exampleCTSSs,
                  subject = exampleUnidirectional,
                  select="arbitrary")

# Aggregate rows and compare
sparse_res <- utilsAggregateRows(sparse_matrix, grp)
dense_res <- utilsAggregateRows(dense_matrix, grp)
all(sparse_res == dense_res)

# Note that storage type was converted to integers!
storage.mode(sparse_res)
storage.mode(dense_res)

# You can also elect to keep a sparse representation
utilsAggregateRows(sparse_matrix, grp, sparse = TRUE)

#### Examples with unused levels ####

# Silly example
dense_mat <- replicate(5, runif(10))
sparse_mat <- as(dense_mat, "dgCMatrix")
fct_unused <- factor(c(1, 1, NA, NA, 3, 3, NA, NA, 5, 5), levels=1:5)

# The default is to drop unused levels
utilsAggregateRows(dense_mat, fct_unused, drop=TRUE)
utilsAggregateRows(sparse_mat, fct_unused, drop=TRUE)

# For dgCMatrix, one can elect to retain these:
utilsAggregateRows(sparse_mat, fct_unused, drop=FALSE)

# For matrix, a warning is produced if either drop or sparse is requested
utilsAggregateRows(dense_mat, fct_unused, drop=FALSE)
utilsAggregateRows(dense_mat, fct_unused, sparse=TRUE)
}
\seealso{
Other Utility functions: 
\code{\link{utilsDeStrand}()},
\code{\link{utilsScoreOverlaps}()},
\code{\link{utilsSimplifyTxDb}()}
}
\concept{Utility functions}
