Rev 38044 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
\name{rowsum}\alias{rowsum}\alias{rowsum.default}\alias{rowsum.data.frame}\title{Give row sums of a matrix or data frame, based on a grouping variable}\description{Compute sums across rows of a matrix-like object for each level of a groupingvariable. \code{rowsum} is generic, with methods for matrices and dataframes.}\usage{rowsum(x, group, reorder = TRUE, \dots)\method{rowsum}{data.frame}(x, group, reorder = TRUE, na.rm = FALSE, \dots)\method{rowsum}{default}(x, group, reorder = TRUE, na.rm = FALSE, \dots)}\arguments{\item{x}{a matrix, data frame or vector of numeric data. Missingvalues are allowed. A numeric vector will be treated as a column vector.}\item{group}{a vector giving the grouping, with one element per row of\code{x}. Missing values will be treated as another group and awarning will be given.}\item{reorder}{if \code{TRUE}, then the result will be in order of\code{sort(unique(group))}, if \code{FALSE}, it will be in the orderthat rows were encountered. }\item{na.rm}{logical (\code{TRUE} or \code{FALSE}). Should \code{NA}values be discarded?}\item{\dots}{other arguments for future methods}}\value{A matrix or data frame containing the sums. There will be one row perunique value of \code{group}.}\details{The default is to reorder the rows to agree with \code{tapply} as inthe example below. Reordering should not add noticeably to the timeexcept when there are very many distinct values of \code{group} and\code{x} has few columns.The original function was written by Terry Therneau, but this is anew implementation using hashing that is much faster for large matrices.To add all the rows of a matrix (ie, a single \code{group}) use\code{\link{rowSums}}, which should be even faster.}\seealso{\code{\link{tapply}}, \code{\link{aggregate}}, \code{\link{rowSums}}}\examples{x <- matrix(runif(100), ncol=5)group <- sample(1:8, 20, TRUE)xsum <- rowsum(x, group)## Slower versionsxsum2 <- tapply(x, list(group[row(x)], col(x)), sum)xsum3 <- aggregate(x, list(group) ,sum)}\keyword{manip}