\Header{rowsum}{Give Row Sums of a Matrix, Based on a Grouping Variable}
\keyword{manip}{rowsum}
\begin{Description}\relax
Compute sums across rows of a matrix for each level of a grouping
variable.\end{Description}
\begin{Usage}
\begin{verbatim}
rowsum(x, group, reorder = TRUE)
\end{verbatim}
\end{Usage}
\begin{Arguments}
\begin{ldescription}
\item[\code{x}] a matrix or vector of numeric data.  Missing values are
allowed.
\item[\code{group}] a vector giving the grouping, with one element per row of
\code{x}.  Missing values are not allowed.
\item[\code{reorder}] if \code{TRUE}, then the result will be in order of
\code{sort(unique(group))}, if \code{FALSE}, it will be in the order
that rows were encountered (and may run faster for large matrices).
The default is to reorder the data, so as to agree with
\code{tapply} (see example below).
\end{ldescription}
\end{Arguments}
\begin{Value}
a matrix containing the sums.  There will be one row per unique value
of \code{group}.\end{Value}
\begin{Author}\relax
Terry Therneau\end{Author}
\begin{SeeAlso}\relax
\code{\Link{tapply}}, \code{\Link{rowSums}}\end{SeeAlso}
\begin{Examples}
\begin{ExampleCode}
x <- matrix(runif(100), ncol=5)
group <- sample(1:8, 20, TRUE)
xsum <- rowsum(x, group)

## same result another way, slower, and temp may be much larger than x
temp <- model.matrix(~ a - 1, data.frame(a=as.factor(group)))
xsum2<- t(temp) %*% x

## same as last one, but really slow
xsum3 <- tapply(x, list(group[row(x)], col(x)), sum)
\end{ExampleCode}
\end{Examples}

