rowsum                 package:base                 R Documentation

_G_i_v_e _R_o_w _S_u_m_s _o_f _a _M_a_t_r_i_x, _B_a_s_e_d _o_n _a _G_r_o_u_p_i_n_g _V_a_r_i_a_b_l_e

_D_e_s_c_r_i_p_t_i_o_n:

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

_U_s_a_g_e:

     rowsum(x, group, reorder = TRUE)

_A_r_g_u_m_e_n_t_s:

       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).

_V_a_l_u_e:

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

_A_u_t_h_o_r(_s):

     Terry Therneau

_S_e_e _A_l_s_o:

     `tapply'

_E_x_a_m_p_l_e_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)

