

   rowsum {base}                                R Documentation

   GGiivvee RRooww SSuummss ooff aa MMaattrriixx,, BBaasseedd oonn aa GGrroouuppiinngg VVaarriiaabbllee

   UUssaaggee::

        rowsum(x, group, reorder=T)

   AArrgguummeennttss::

          x: a matrix or vector of numeric data.  Missing val-
             ues 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).

   VVaalluuee::

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

   AAuutthhoorr((ss))::

        Terry Therneau

   SSeeee AAllssoo::

        `tapply'

   EExxaammpplleess::

        x <- matrix(runif(100), ncol=5)
        group <- sample(1:8, 20, T)
        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)

