This help topic is for R version 1.5.0. For the current version of R, try https://stat.ethz.ch/R-manual/R-patched/library/base/html/rowsum.html
rowsum {base}R Documentation

Give Row Sums of a Matrix, Based on a Grouping Variable

Description

Compute sums across rows of a matrix for each level of a grouping variable.

Usage

rowsum(x, group, reorder = TRUE)

Arguments

x

a matrix or vector of numeric data. Missing values are allowed.

group

a vector giving the grouping, with one element per row of x. Missing values are not allowed.

reorder

if TRUE, then the result will be in order of sort(unique(group)), if 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 tapply (see example below).

Value

a matrix containing the sums. There will be one row per unique value of group.

Author(s)

Terry Therneau

See Also

tapply, rowSums

Examples

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)

[Package base version 1.5.0 ]